Pergunta

Using method chaining I would like to amend the following code so that on each iteration the variables mult and n are printed. What method can help accomplish this?

(1..3).inject {|mult, n| mult * n}
Foi útil?

Solução

Enumerable#tap is what you need

(1..3).inject { |mult, n| (mult * n).tap { |next_mult| p [n, mult, next_mult] } }

Outras dicas

This looks simpler to me than the tap solution. It may be a matter of taste.

(1..3).inject do |mult, n|
  puts "#{mult} #{n}"
  mult * n
end

1 2
2 3
=> 6

To answer bodhidarma's other question about the number of iterations, the docs say:

If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.

Like this:

>> (1..3).inject {|mult, n| r =  mult * n; p "mult = #{mult}, n = #{n}, mult * n = #{r}"; r}
"mult = 1, n = 2, mult * n = 2"
"mult = 2, n = 3, mult * n = 6"
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top