We usually use block arguments like so:
[[1, 2, 3], [4, 5, 6]].map { |arr| arr[0] }
=> [1, 4]
We also know that we can deconstruct the arguments using the splat operator, like so:
[[1, 2, 3], [4, 5, 6]].map { |first, *rest| rest }
=> [[2, 3], [5, 6]]
But what I recently found it is that we can also deconstruct block arguments like so:
[[1, 2, 3], [4, 5, 6]].map { |first, second, third| first }
=> [1, 4]
We can also group arguments up with parentheses to deconstruct them, like so:
{foo: "bar", bim: "baz"}.each_with_object({}) { |(key, val), memo| memo[key] = [key, val] }
=> {:foo=>[:foo, "bar"], :bim=>[:bim, "baz"]}
Top comments (0)