通过引用的Ruby调用在每个函数中都不起作用?

时间:2011-06-16 07:41:36

标签: ruby-on-rails ruby ruby-on-rails-3

excluded = "a", " an", " the", " at", " in", " on ", "since"     
temp = excluded.split(",").each {|val|  val = val.strip}

但是我得到了相同的数组。它没有条纹。我需要用单行

来做这件事

我需要临时输出,如[“a”,“an”,“the”,“at”,“in”,“on”,“since”]

4 个答案:

答案 0 :(得分:4)

试试这个

 temp =  ["a", " an", " the", " at", " in", " on ", "since"].map(&:strip)

答案 1 :(得分:3)

the docs Array#each可以看到,返回原始接收者(ary.each {|item| block } → ary)。正如其他人已经指出的那样,你想要的是Array#map

由于在数组上调用split,您当前的代码也应该引发NoMethodError。假设excluded是一个字符串,以下内容将起作用:

excluded.split(",").map(&:strip) #=> ["a", "an", "the", "at", "in", "on", "since"]

您也可以只更改拆分的内容,而不是使用strip

excluded.split(/,\s*/) #=> ["a", "an", "the", "at", "in", "on", "since"]

答案 2 :(得分:1)

你想要这个吗?:

excluded = ["a", " an", " the", " at", " in", " on ", "since"]
stripped_excluded = excluded.collect{ |i| i.strip }

或捷径:

stripped_excluded = excluded.collect(&:strip)

答案 3 :(得分:0)

我认为这应该是更简单的方法:

temp = excluded.map(&:strip)
p temp