2011-06-16 98 views
0
excluded = "a", " an", " the", " at", " in", " on ", "since"  
temp = excluded.split(",").each {|val| val = val.strip} 

但我得到相同的数组。它不是条纹。我需要这样做在单线Ruby通过引用调用不在每个函数中工作?

我需要在温度输出像[“a”,“an”,“the”,“at”,“in”,“on”,“since”]

+0

你想做什么?请显示您的预期输出应该是什么。 – Zabba 2011-06-16 07:46:07

+0

我需要像[“a”,“an”,“the”,“at”,“in”,“on”,“since”]在temp中的输出 – Sreeraj 2011-06-16 07:48:22

+0

您正在使用哪个版本的ruby? – 2011-06-16 07:51:19

回答

3

正如你所见,从the docsArray#each返回原始接收器(ary.each {|item| block } → ary)。你想要的 - 正如其他人已经指出的 - 是Array#map

此外,由于调用数组上的拆分,您当前的代码应该引发NoMethodError。假设excluded是一个字符串,下面的工作:

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

而不是使用strip的你也可以改变你的劈在了什么:

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

谢谢迈克尔,你刚刚完成了一项出色的工作。非常感谢 – Sreeraj 2011-06-16 08:27:21

1

你要这个?:

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

或快捷方式:

stripped_excluded = excluded.collect(&:strip) 
+0

感谢您的文章:) – Sreeraj 2011-06-16 08:35:51

4

试试这个

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

感谢您的文章 – Sreeraj 2011-06-16 08:39:11

0

我想,这应该是更简单的方法:

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

感谢您的发帖 – Sreeraj 2011-06-16 08:36:26