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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:22:16  来源:igfitidea点击:

remove whitespace from each array item rails

ruby-on-railsrubyarrays

提问by Toby Joiner

I found this code:

我找到了这个代码

.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

https://ruby-doc.org/core/String.html#method-i-strip

https://ruby-doc.org/core/String.html#method-i-strip

回答by Gvlamadrid

If you don't mind first removing nilelements:

如果您不介意先删除nil元素

YourArray.compact.collect(&:strip) 

https://ruby-doc.org/core/Array.html#method-i-compact

https://ruby-doc.org/core/Array.html#method-i-compact

回答by Aparichith

If you are using Rails, consider squish:

如果您使用 Rails,请考虑squish

Returns the string, first removing all whitespace on both ends of the string, and then changing remaining consecutive whitespace groups into one space each.

返回字符串,首先删除字符串两端的所有空格,然后将剩余的连续空格组更改为一个空格。

yourArray.collect(&:squish)

回答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]