excluded = "a", " an", " the", " at", " in", " on ", "since"
temp = excluded.split(",").each {|val| val = val.strip}
但我得到了相同的数组。它不是条纹。我需要在单行中完成此操作
我需要temp中的输出,如["a"、"an"、"the"、"at"、"in"、"on"、"since"]
尝试这个
temp = ["a", " an", " the", " at", " in", " on ", "since"].map(&:strip)
正如您从文档中看到的,Array#each
返回原始接收器(ary.each {|item| block } → ary
(。正如其他人已经指出的那样,您想要的是数组#映射。
此外,由于在数组上调用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"]
你想要这个吗?:
excluded = ["a", " an", " the", " at", " in", " on ", "since"]
stripped_excluded = excluded.collect{ |i| i.strip }
或快捷方式:
stripped_excluded = excluded.collect(&:strip)
我认为这应该是更简单的方法:
temp = excluded.map(&:strip)
p temp