« Back to Index

Passing through key and value to a reduce method block rather than just the item

View original Gist on GitHub

reduce with key and value.rb

# As expected the output is the key, then the value...

({ :key => :value, :foo => :bar }).reduce([]) { |pass_through, item|
  puts item
}

# key
# value
# foo
# bar

# The following example is better, as we get the key AND value passed through at once...

({ :key => :value, :foo => :bar }).reduce([]) { |pass_through, (item_key, item_val) |
  puts "#{item_key} / #{item_val}"
}

# key / value
# foo / bar