DEV Community

Augusts Bautra
Augusts Bautra

Posted on

TIL: Explode Hash keys into variables in Ruby 3.2+

Oftentimes we're looping over an array of hashes:

data = [{a: 1}, {a: 2}]
data.each do |data|
  some_logic(data[:a])
  # OR
  a = data[:a]
  some_logic(a)
end
Enter fullscreen mode Exit fullscreen mode

But what if we have several keys in the hash? Assigning everything to a variable can get verbose.

Luckily, modern Ruby provides a neat way to explode the data in a oneliner:

data = [{a: 1}, {a: 2}]
data.each do |data|
  data => { a: }
  some_logic(a)  
end
Enter fullscreen mode Exit fullscreen mode

Furthermore, you can specify a custom variable name to use:

data = [{a: 1}, {a: 2}]
data.each do |data|
  data => { a: the_value }
  some_logic(the_value)  
end
Enter fullscreen mode Exit fullscreen mode

Finally, nested hashes can also be exploded easily:

data = [{namespace: {foo: 1, bar: {baz: 2}}}]
data.each do |data|
  data => { namespace: { foo:, bar: { baz: } } }
  # Only terminal nodes without further nesting get variables
  some_logic(foo, baz)  
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)