D
D
Demigodd2019-05-07 12:56:00
Ruby on Rails
Demigodd, 2019-05-07 12:56:00

How to search by hash in Ruby?

For example, there is such a hash:

var = {
  "aaa"=>{"age"=>11},
  "bbb"=>{
    "age"=>11,
    "children"=>{
      "child_1"=>{"age"=>11},
      "child_2"=>{"age"=>11}
    }
  },
  "ccc"=>{"age"=>11}
}

For example, in var you need to find the child_2 property and get it.
That is, how to write a function that will search the entire hash, including children.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mirilaczvili, 2019-05-07
@Demigodd

If the hash structure is known in advance and the location of child_2 does not change internally, then in Ruby 2.3+ you can simply do this:
var.dig("bbb", "children", "child_1")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question