vendredi 7 août 2015

need an easier way to initialize nested hashes in ruby rather than assignment at each deeper level

I'm new to the ruby landscape and have found a lot of difficulty working with hashes. It seems there are a lot of ways to do the same thing in ruby, but what I'm having trouble with is assigning hashes at sub levels in an existing hash.

For example in my class I have the following code:

@query_hash = {"term" => {"field" => "value"}
@main_hash["query"]["filtered"]["query"]["bool"] = @query_hash

The problem is that there are times where one of the sub-hashes are missing in the @main_hash so the above path would have a key such as "filtered" or "query" missing in @main_hash and I'd get a nil related exception. So what I have had to do is check for each level of nestation first before referencing the next as I go deeper in the hash. If the level doesn't exist I have to initialize that sub-hash in an ugly way like this: @main_hash["query"] = {"filtered" => {"query" => "bool"}}

Is there a more cleaner and simpler way to deal with this kind of hash munging?

Aucun commentaire:

Enregistrer un commentaire