|||

Deconstructing Block Arguments In Ruby

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"]}
Up next Inspecting Ruby Method Params At work, a colleague of mine created a gem that our company’s codebase uses. It inspects the Ruby background job classes we have and presents them Decorating Service Objects - FunctionalObject A common pattern used in Ruby programs are Service Objects. They help enforce the Single-responsibility Principle throughout the app, which in turn
Latest posts Decorating Service Objects - FunctionalObject Deconstructing Block Arguments In Ruby Inspecting Ruby Method Params