Ruby-on-rails 从每个数组项 rails 中删除空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3926190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
remove whitespace from each array item rails
提问by Toby Joiner
.each_key {|a| self[a].strip! if self[a].respond_to? :strip! }
...but it is for a hash, whereas I am trying to do the same with an array.
...但它用于散列,而我试图对数组执行相同的操作。
回答by Jamie Wong
This is what collectis for.
这collect就是为了。
The following handles nilelements by leaving them alone:
以下通过不理会nil元素来处理元素:
yourArray.collect{ |e| e ? e.strip : e }
If there are no nilelements, you may use:
如果没有nil元素,您可以使用:
yourArray.collect(&:strip)
...which is short for:
...这是以下的简称:
yourArray.collect { |e| e.strip }
strip!behaves similarly, but it converts already "stripped" stringsto nil:
strip!行为类似,但它将已经“剥离”的字符串转换为nil:
[' a', ' b ', 'c ', 'd'].collect(&:strip!)
=> ["a", "b", "c", nil]
https://ruby-doc.org/core/Array.html#method-i-collect
https://ruby-doc.org/core/Array.html#method-i-collect
回答by Gvlamadrid
If you don't mind first removing nilelements:
如果您不介意先删除nil元素:
YourArray.compact.collect(&:strip)
回答by Aparichith
回答by Nikita Rybak
Adapting the approach you found, from working on a hash to working on an array:
调整您发现的方法,从处理散列到处理数组:
[' c ', 'd', nil, 6, false].each { |a| a.strip! if a.respond_to? :strip! }
=> ["c", "d", nil, 6, false]

