Thursday, August 16, 2012

Ruby: split a string


If we want to split a string with the space as the delimiter, we can use something like:
irb(main):005:0> "a b  c   d    ".split(' ')
=> ["a", "b", "c", "d"]

It does not matter whether the separator is only a single whitespace character or multiple whitespace characters. The contiguous whitespace characters are treated as one delimiter. And the trailing whitespace characters are all discarded.

The interesting thing is that only the whitespace characters are handled in this way. If we change the whitespace characters into commas, the result is different:
irb(main):006:0> "a,b,,c,,,d,,,,".split(',')
=> ["a", "b", "", "c", "", "", "d"]

Every single comma is treated as one delimiter, no matter whether there is anything between two commas. The trailing commas are all ignored as well if there are nothing among them.

How can we get the same result as the comma separated string from the whitespace separated one? We can, with the help of regular expression:
irb(main):007:0> "a b  c   d    ".split(/ /)
=> ["a", "b", "", "c", "", "", "d"]

1 comment:

Anonymous said...

Hallo i would suggest to add a right bottom menu for transalting text seletion in a pop windows.
This only when i choose the menu comand, not just with rollover on right bottom mouse.
At the present all pop windows are not friendly because they interfere with the context menu, or come out when i don't need. thanks

 
Get This <