Home > Back-end >  Can someone explain me what this line of ruby code does?
Can someone explain me what this line of ruby code does?

Time:10-16

I'm a beginner in ruby and found this example on the Odin project about the reduce method, but in line 7 it puts the result variable again, can someone explain me What's the use of putting the result variable?

Thank you in advance!

votes = ["Bob's Dirty Burger Shack", "St. Mark's Bistro", "Bob's Dirty Burger Shack"]

votes.reduce(Hash.new(0)) do |result, vote|
  puts "result is #{result} and votes is #{vote}"
  puts "This is result [vote]: #{result[vote]}"
  result[vote]  = 1
  result #this part I don't understand
end

CodePudding user response:

They're using the reduce(initial_operand) {|memo, operand| ... } version.

memo is a thing to collect the result. The block has to pass that along to the next iteration. For example, if you wanted to sum up a list of numbers...

(1..4).inject do |sum, element|
  p "Running sum: #{sum}; element: #{element}"

  # This is passed along to the next iteration as sum.
  sum   element
end

Instead of using the default memo, which would be the first element, they've used Hash.new(0) to count the votes. Each iteration counts the votes, and then passes the result has to the next iteration.

# result starts as Hash.new(0)
votes.reduce(Hash.new(0)) do |result, vote|
  # This prints the state of the voting and the current choice being tallied.
  puts "result is #{result} and votes is #{vote}"

  # This displays how many votes there are for this choice at this point
  # before this choice is tallied.
  puts "This is result [vote]: #{result[vote]}"

  # This adds the vote to the tally.
  result[vote]  = 1

  # This passes along the tally to the next iteration.
  result
end

If you don't want to print on each iteration, use tally instead.

result = votes.tally
  • Related