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

words是一个包含许多单词的数组。我的代码正在删除“a”,但没有删除“for”、“to”或“and”。

4

3 回答 3

8

愿这对你有帮助

words.delete_if do |x|
  %w(a for to and).include?(x)
end
于 2012-10-19T07:35:00.477 回答
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"] 
于 2012-10-19T07:34:52.127 回答
5

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

w = %W{a 结束}

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

于 2012-10-19T07:40:42.567 回答