我有一个单字串数组,我想在每个单字串的末尾添加一个“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"]
最佳答案
您应该清楚地区分改变接收者(调用它们的变量)的方法与纯没有副作用的方法。此外,如果您要使用该方法的结果,您应该关心该方法返回的内容。
此处所有索引(但1
)的方法都返回“s”
,因为它是 block 返回的内容:
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
与其就地改变数组,首选的解决方案是返回修改后的版本。为此,您应该从 block 中返回新值:
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"]
关于ruby - 将 "s"添加到数组中除给定数组中的第二个元素之外的每个单词的末尾,仅使用一行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53909400/