Ruby delete_if多个值 - 只删除第一个值

时间:2012-10-19 07:32:39

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

words.delete_if do |x|
  x == ("a"||"for"||"to"||"and")
end

words是一个包含很多单词的数组。我的代码是删除“a”但不删除“for”,“to”或“and”。

3 个答案:

答案 0 :(得分:8)

愿这会帮到你

words.delete_if do |x|
  %w(a for to and).include?(x)
end

答案 1 :(得分:7)

只做

words - ["a", "for", "to", "and"]

实施例

words = %w(this is a just test data for array - method and nothing)
 => ["this", "is", "a", "just", "test", "data", "for", "array", "-", "method", "and", "nothing"] 
words = words - ["a", "for", "to", "and"]
 => ["this", "is", "just", "test", "data", "array", "-", "method", "nothing"] 

答案 2 :(得分:5)

如果你跑步" a" || " B"在irb然后你将永远得到" a"因为它是一个非空值,它将由||返回总是.. 在你的情况下" a" ||"对于"将始终评估" a"不管数组中的其他值如何.. 所以这是我对你的问题的替代解决方案

w =%W {a for to end}

words.reject! {| x | w.include?(x)}