我已经完成了Rails的开发工作,但是已经有一段时间了。
除了求和值(我在网上看到的主要例子)之外,我从未使用过reduce / inject,但我想更好地了解它的作用(还有tbh,仅是它的语法)。
我听说它被称为红宝石的functional
部分,但基于示例,不确定这是什么意思。
看一下文档中的示例(最长的单词示例)https://ruby-doc.org/core-2.4.0/Enumerable.html#method-i-reduce似乎暗示它对于从序列末尾选择一个值很有用,但这似乎不是很functional
。
我的理解是,它累积到传递给reduce的初始值。但是在此代码片段中,我不确定为什么它没有累积(我期望“某些乔鸟乔蜜蜂”或某些变体)。
# expect 'some joe birds joe bees'
def say_joe(name)
puts "within say_joe #{name}"
" joe #{name}"
end
a = %w(birds bees)
starting = "some"
b = a.reduce(starting) do |total, x|
puts x
say_joe(x)
end
puts "-----"
puts "starting: #{starting}"
puts "a: #{a}"
puts "b: #{b}"
输出:
birds
within say_joe birds
bees
within say_joe bees
-----
starting: some
a: ["birds", "bees"]
b: joe bees
reduce的魔力是什么?
答案 0 :(得分:0)
累积(在这种情况下为字符串串联)不会自动发生。您仍然需要返回新的累加器值(在Ruby中请记住,最后一条语句也隐式地是返回值)。
这符合您的期望
def say_joe(name)
puts "within say_joe #{name}"
" joe #{name}"
end
a = %w(birds bees)
starting = "some"
b = a.reduce(starting) do |total, x|
puts x
total << say_joe(x)
end
puts "-----"
puts "starting: #{starting}"
puts "a: #{a}"
puts "b: #{b}” # some joe birds joe bees