DEV Community

Discussion on: The Case for Pattern Matching Key Irreverence in Ruby

Collapse
 
mculp profile image
Matt Culpepper

I'm just digging into pattern matching today for no real reason. I was trying to see if there was a cleaner way to write this with pattern matching:

h = { data: [{ id: 1 }, { id: 2 }] }
ids = h[:data].map { |data| data[:id] }
Enter fullscreen mode Exit fullscreen mode

After digging through the docs, this is as close as I've gotten, but it only grabs the first id. Do you know if there's a way to match and assign all ids?

h = { data: [{ id: 1 }, { id: 2 }] }
h => data: [{id: ids]}, *]

> ids
1
Enter fullscreen mode Exit fullscreen mode
Collapse
 
baweaver profile image
Brandon Weaver

With how pattern matching works, no, unfortunately. There can't be guarantees the next objects in that Array are all of the same structure or even type, so each subsequent node has either deconstruct or deconstruct_keys called on it.

Now that said you might enjoy jq and the Ruby wrapper around it: github.com/winebarrel/ruby-jq

I've been musing about my own DSL for searching through deeply nested structures because that's always a pain, but haven't experimented too much on it yet.