首页 > 解决方案 > 将“s”添加到数组中每个单词的末尾,给定数组中的第二个元素除外,仅使用一行代码

问题描述

我有一个单词字符串数组,我想在每个单词字符串的末尾添加一个“s”,除了数组中的第二个字符串(元素)。我可以使用 9 行代码轻松完成此操作,但更愿意使用 3 行代码来完成。

这是我使用 9 行的工作代码。

def add_s(array)
    array.each_with_index.collect do |element, index|
        if index == 1
            element
        else element[element.length] = "s"
            element
        end
    end
end

这是我仅尝试使用 3 行时损坏的代码。

def add_s(array)
    array.each_with_index.map {|element, index| index == 1 ? element : element[element.length] = "s"}
end

以上将返回...

array = ["hand", "feet", "knee", "table"]
add_s(array) => ["s", "feet", "s", "s"]

我试图得到...

array = ["hand", "feet", "knee", "table"]
add_s(array) => ["hands", "feet", "knees", "tables"]

标签: rubyeachternary-operatorcollect

解决方案


您应该清楚地区分改变接收器的方法(调用它们的变量)与没有副作用的纯方法。此外,如果要使用方法的结果,您应该关心方法返回的内容。

这里所有索引 (but 1) 的方法都返回"s",因为它是块返回的内容:

foo = "bar"
foo[foo.length] = "s"
#⇒ "s"

如果您之后检查您的变异数组,您会看到它已成功修改为您想要的。

input = %w[hand feet knee table]
def add_s(input)
  input.each_with_index.map do |element, index|
    index == 1 ? element : element[element.length] = "s"
  end
  input # ⇐ HERE :: return the mutated object
end
#⇒ ["hands", "feet", "knees", "tables"]

甚至更简单,不要映射,只需迭代和变异:

input = %w[hand feet knee table]
def add_s(input)
  input.each_with_index do |element, index|
    element[element.length] = "s" unless index == 1
  end
end

首选的解决方案是返回修改后的版本,而不是就地改变数组。为此,您应该从块中返回新值:

def add_s(input)
  input.each_with_index.map do |element, index|
    index == 1 ? element : element + "s"
  end
end
#⇒ ["hands", "feet", "knees", "tables"]

如果给我这样的任务,我也会维护一个要跳过的元素列表,因为迟早会有多个:

input = %w[hand feet knee scissors table]
to_skip = [1, 3]
def add_s(input)
  input.each_with_index.map do |element, index|
    next element if to_skip.include?(index)
    element + "s"
  end
end
#⇒ ["hands", "feet", "knees", "scissors", "tables"]

推荐阅读