DEV Community

Daniel Goh
Daniel Goh

Posted on

Deconstructing Block Arguments In Ruby

We usually use block arguments like so:

[[1, 2, 3], [4, 5, 6]].map { |arr| arr[0] }
=> [1, 4]
Enter fullscreen mode Exit fullscreen mode

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]]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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"]}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)