ruby - 将“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"]
解决方案
您应该清楚地区分改变接收器的方法(调用它们的变量)与没有副作用的纯方法。此外,如果要使用方法的结果,您应该关心方法返回的内容。
这里所有索引 (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"]
推荐阅读
- python - 结合loc和groupby后的Pandas多维键错误
- xcode - 在 project_root/ios/Pods/Flipper-Boost-OSX/frameworks/boost.xcframework 找不到 XCFramework
- macos - 将 Openssl 1.1.1 设置为默认版本
- graphql - 根据请求刷新令牌
- python - 使用 vscode 下载 MNIST 数据
- load-balancing - 使用一致性哈希时,何时在我的系统设计中添加负载均衡器?
- .net - 使用 .NET 将多个项目插入 DynamoDB 表
- javascript - destructured prop 中的 className 有时不适用于组件,这是一个错误吗?(下一个.JS)
- outlook - Exchange 中的 message-id 和 network-message-id 有什么区别
- google-search - 可以在 Google 搜索中明确搜索哪些文件类型?