sbs
sbs

Reputation: 4152

Extract Hash values using Hash#dig

h = {
  users: {
    u_548912: {
      name: "John",
      age: 30
    },
    u_598715: {
      name: "Doe",
      age: 30
    }
  }
}

Given a hash like above, say I want to get user John, I can do

h[:users].values.first[:name]    # => "John"

In Ruby 2.3 use Hash#dig can do the same thing:

h.dig(:users, :u_548912, :name)  # => "John"

But given that the u_548912 is just a random number(no way to know it before hand), is there a way to get the information still using Hash#dig?

Upvotes: 0

Views: 834

Answers (1)

Drenmi
Drenmi

Reputation: 8777

You can, of course, pass an expression as an argument to #dig:

h.dig(:users, h.dig(:users)&.keys&.first, :name)
#=> John

Extract the key if you want more legibility, at the cost of lines of code:

first_user_id = h.dig(:users)&.keys&.first
h.dig(:users, first_user_id, :name)
#=> John

Another option would be to chain your #dig method calls. This is shorter, but a bit less legible.

h.dig(:users)&.values&.dig(0, :name)
#=> John

I'm afraid there is no "neater" way of doing this while still having safe navigation.

Upvotes: 2

Related Questions