【问题标题】:Ruby delete_if multiple values - only first value being deletedRuby delete_if 多个值 - 仅删除第一个值
【发布时间】:2012-10-19 07:32:39
【问题描述】:
words.delete_if do |x|
  x == ("a"||"for"||"to"||"and")
end

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

【问题讨论】:

  • FWIW,您要执行的逻辑将表示为x == 'a' || x == 'for' || x == 'to' || x == 'and'

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


【解决方案1】:

希望对你有帮助

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

【讨论】:

    【解决方案2】:

    做事

    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"] 
    

    【讨论】:

      【解决方案3】:

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

      w = %W{a 结束}

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 2021-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多