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

Nic*_*5a1 2 ruby ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

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

old*_*god 8

愿这对你有所帮助

words.delete_if do |x|
  %w(a for to and).include?(x)
end
Run Code Online (Sandbox Code Playgroud)


Sal*_*lil 7

做就是了

words - ["a", "for", "to", "and"]
Run Code Online (Sandbox Code Playgroud)

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"] 
Run Code Online (Sandbox Code Playgroud)


Adi*_*oor 5

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

w =%W {a for to end}

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