2012-08-05 95 views
0

以下代码分裂阵列上:地带收集红宝石

str = "1, hello,2" 
puts str 
arr = str.split(",") 
puts arr.inspect 
arr.collect { |x| x.strip! } 
puts arr.inspect 

产生以下结果:

1, hello,2 
["1", " hello", "2"] 
["1", "hello", "2"] 

这被预期。下面的代码:

str = "1, hello,2" 
puts str 
arr = (str.split(",")).collect { |x| x.strip! } 
puts arr.inspect 

但是是否产生以下的输出:

1, hello,2 
[nil, "hello", nil] 

为什么我得到这些 “无”?为什么我不能立即在分割数组上执行.collect?

感谢您的帮助!

+0

对于它的价值,你可以使用正则表达式''1,hello,2“.split(/ \,\ s | \,/)来做同样的事情' – 2012-08-05 17:24:49

回答

1

#collect方法将返回每个块的调用返回的值的数组。在你的第一个例子中,你用#strip!修改了实际的数组内容并使用它们,而忽略了#collect的返回值。

在第二种情况下,您使用#collect结果。你的问题是,#strip!将返回一个字符串或nil,这取决于它的结果 - 尤其是,如果字符串未被修改,它将返回nil

因此,使用#strip(不带感叹号):

1.9.3-p194 :005 > (str.split(",")).collect { |x| x.strip } 
=> ["1", "hello", "2"] 
+0

太棒了。奇迹般有效。谢谢! – beetree 2012-08-05 16:34:18

1

因为#strip!返回nil如果字符串没有改变。

在你早期的例子中,你没有使用#collect,的结果,只是用#strip!修改字符串。在这种情况下使用#each会使非功能性命令循环更加清晰。仅当使用生成的新阵列时,通常只使用#map/#collect

你最后的做法看起来不错,你写了一张功能图,但你离开#strip!在...只是拿出!