【问题标题】:Take an array of words, return the array of words not exceeding max_length characters (reject)取一个单词数组,返回不超过max_length个字符的单词数组(reject)
【发布时间】:2022-11-10 18:38:52
【问题描述】:

我正在做一个练习,我需要使用 .reject 对数组中的某些项目进行排序。 这是我正在尝试的代码:

def short_words(array, max_length)
  array.reject { |words, value| words if value > max_length }
end

TODO:取一个单词数组,返回不超过max_length个字符的单词数组。您应该使用 Enumerable#reject。

【问题讨论】:

标签: arrays ruby


【解决方案1】:

该数组是单词列表。 reject 方法一一接受这些词,并决定要拒绝哪些词。因此,在块中将它们称为|word| 会更清楚。要确定字符串的数量恰好有一个size 方法(word.size)。 value 完全没有必要。

【讨论】:

    【解决方案2】:

    只需在数组中的每个字符串上使用.size 并将其与您进行比较max_length

    array = %w(spain france ireland uk bosnia portugal)
    array.reject { |term| term.size > 5 }
    => ["spain", "uk"]
    

    【讨论】:

      猜你喜欢
      • 2014-03-29
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多