The following code:
str = "1, hello,2"
puts str
arr = str.split(",")
puts arr.inspect
arr.collect { |x| x.strip! }
puts arr.inspect
produces the following result:
1, hello,2
["1", " hello", "2"]
["1", "hello", "2"]
This is as expected. The following code:
str = "1, hello,2"
puts str
arr = (str.split(",")).collect { |x| x.strip! }
puts arr.inspect
Does however produce the following output:
1, hello,2
[nil, "hello", nil]
Why do I get these “nil”? Why can’t I do the .collect immediately on the splitted-array?
Thanks for the help!
The
#collectmethod will return an array of the values returned by each block’s call. In your first example, you’re modifying the actual array contents with#strip!and use those, while you neglect the return value of#collect.In the second case, you use the
#collectresult. Your problem is that#strip!will either return a string ornil, depending on its result – especially, it’ll returnnilif the string wasn’t modified.Therefore, use
#strip(without the exclamation mark):