Prevent String#split from throwing away empty trailing elements

Sunday, January 16, 2011

The default behavior of String#split will throw away any trailing
values if they are empty.

> "Hello,There,,".split(',') 
=> ["Hello", "There"]

If you want to keep those empty trailing elements, pass a negative
number for the second (limit) parameter.

> "Hello,There,,".split(',', -1)
=> ["Hello", "There", "", ""]

This tip was submitted by two-bit-fool. via

This entry was tagged Ruby and tips

comments powered by Disqus

© 2009-2013 All rights reserved. Powered by Pyramid

go to Top