Robbo
Robbo

Reputation: 1312

Best way to access the values of a nested hash

Here is my hash:

{"funds"=>
  {"0"=>
    {"sector"=>"6555",
     "fund_id"=>"4308",
     "percent"=>"20.0",
     "fund_distribution_id"=>"315304"
    }
  }
}

How do I get the values for sector, fund_id etc?

If I do the following I get an undefined method '[]' nil:NilClass because it's looking for the 'sector' key of '0'

params[:funds].each_with_index do |f, index|
    puts f[index]['sector']
end

Upvotes: 1

Views: 1082

Answers (4)

bbozo
bbozo

Reputation: 7301

I usually extend the Hash class with this:

class Hash
  def deep_fetch *args
    args.inject(self) { |h, val| h.try(:[], val) }
  end
end

and then you can call:

my_hash.deep_fetch 'funds', 0, 'sector'

to get funds->0->sector or you'll get nil if its not there

or in your case:

(my_hash.deep_fetch('funds', 0) || {}).each{ ... }

Upvotes: 2

alek
alek

Reputation: 331

Try this:

x['funds'].values.map{ |fund| fund['sector'] }
x['funds'].values.map{ |fund| fund['fund_id'] }
# etc.

Where "x" is your given hash

Upvotes: 2

Shalev Shalit
Shalev Shalit

Reputation: 1963

You need to do index.to_s to get to your hash with string hash, as shown.

If you want all values, you can use hash.values.

If you don't want to get error for nil use hash.try(:[], value)

Upvotes: 1

Atul
Atul

Reputation: 268

if

x = {"funds"=>
      {"0"=>
        {"sector"=>"6555", 
         "fund_id"=>"4308", 
         "percent"=>"20.0", 
         "fund_distribution_id"=>"315304"
        }
      }
    }

, then you can get value of sector and fund_id by

  x["funds"]["0"]["sector"]
  x["funds"]["0"]["fund_id"]

Upvotes: 2

Related Questions