ruby - Splat block parameters for reduce/inject iterator -
i have defined array this:
ary = [[0,1], [2,3]] running following code:
ary.reduce(nil) |a, i, k| puts "#{a.inspect} #{i.inspect} #{k.inspect}" end at each iteration i'd expect variables a, i, , k hold, respectively, value of accumulator (nil), first element, , second element of inner array, i.e. i'd expect output:
nil 0 1 nil 2 3 but instead result is:
nil [0, 1] nil nil [2, 3] nil why? how can achieve result want?
moreover, why following code using map working expect?
ary.map |i, k| puts "#{i.inspect} #{k.inspect}" end # output # 0 1 # 2 3 what difference?
splat can work 1 level. map, block parameter [0, 1] , on, can spalatted 0 , 1. inject, block parameters nil , [0, 1], may assigned 2 variables (without splat), not three. splat not work here because splatted (they 2 variables). in order splat [0, 1], need within array, requires pair of parentheses.
{|a, (i, j)| ...}
Comments
Post a Comment