2

I have a hash:

a = {
  "person" => [
    {
      "age"     => ["0"],
      "details" => [
        {
          "hobby"    => ["6"],
          "interest" => ["programming"]
        }
      ]
    }
  ]
}

I would like to get the value of the "details". The easy way to do it will be

a["person"].first["details"].first 

But, it is too long and doesn't look good. Is there any other way I can do this?

1
  • the access is ok, the original hash may be improved if those arrays are not really needed. Commented May 24, 2012 at 22:07

2 Answers 2

3

If your search conditions based on structure of hash, the easiest way to do it will be represent this structure in access command what you have done.

If you want several chars less, here it is:

a["person"][0]["details"][0]

If your search conditions based on key names, you can create your own function in Hash class to search over nested hashes and do something like this:

a.search(:details).first

If you don't like square brackets, use https://github.com/intridea/hashie and access data in hash through attributes:

a.person.first.details.first

Anyway, you can do nothing, because your code looks pretty much usual for any rubyist.

Sign up to request clarification or add additional context in comments.

Comments

3

The original code of getting value from the hash looks ok for me. If you want to do something nicer it's only to modify the hash:

a = {"person"=>{"age"=>["0"], "details"=>{"hobby"=>["6"], "interest"=>["programming"]}}}

Then you can get access in better way:

a['person']['details'] #=> {"hobby"=>["6"], "interest"=>["programming"]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.