Home > Enterprise >  Why can't Ruby's reduce method calculate from 2 to 4?
Why can't Ruby's reduce method calculate from 2 to 4?

Time:04-06

I want to perform a simple calculation of 2 3 4, so I wrote the following code. However, when I put the result of list, I only get "2 3 4". May I ask where did I have the problem?

list = [2, 3, 4]

list.reduce(0) {|start, i| start   i }

puts list

CodePudding user response:

method reduce returns the result but you're not using it. list stays your list, reduce do not alter it

list = [2, 3, 4]
sum = list.reduce(0) { |start, i| start   i }
puts sum
  •  Tags:  
  • ruby
  • Related