I have done Rails development a bit but haven't for a while.
I have never used reduce / inject other than to sum up values (which seems to be the main example I've seen online) but would like to understand better what it does (and to be honest, just its syntax). I have heard it referred to as the functional
part of Ruby but based upon examples, not sure what that means.
Looking at the example in the docs (the longest word example) https://ruby-doc.org/core-2.4.0/Enumerable.html#method-i-reduce seems to imply that it is useful for selecting a value out of a series at end but this doesn't seem very functional
.
My understanding is that it accumulates to the initial value passed into reduce. But in this code fragment, I'm not sure why it's not accumulating (I'm expecting "some joe birds joe bees" or some variation).
# 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}"
with output:
birds
within say_joe birds
bees
within say_joe bees
-----
starting: some
a: ["birds", "bees"]
b: joe bees
What is the magic of reduce?
The accumulation (in this case a string concatenation) doesn’t happen automatically. You still need to return the new accumulator value (remember in Ruby the last statement is also implicitly the return value).
This does what you’d expect:
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments