Moeen
Moeen

Reputation: 412

how can fetch data from hash nested array in ruby?

I have an array like:

array = [:a, b: [:c, :d]]
 => [:a, {:b=>[:c, :d]}] 

when i was tried array[:b] i got this error:

TypeError (no implicit conversion of Symbol into Integer)

how can I get :b element from this array?

Note: I don't want to use index to do that (array[1]).

Upvotes: 1

Views: 327

Answers (3)

Moeen
Moeen

Reputation: 412

i think this is the solution

array.last[:b]

in this type of array all (key: val) values will store on last element of array as a hash

for example in:

array = [:a, :b, c: [:d], e: [:f], g: [:h]]
 => [:a, :b, {:c=>[:d], :e=>[:f], :g=>[:h]}] 

I can access the :c element with:

array.last[:c]
 => [:d] 

or

array.select{|x| x.instance_of?(Hash)}.last[:c]
 => [:d]

Upvotes: 0

Gagan Gami
Gagan Gami

Reputation: 10251

Note: I don't want to use index to do that (array[1]).

> array.find{|e| e.is_a?(Hash) && e.has_key?(:b)}
#=> {:b=>[:c, :d]}

or

> array.find{|e| e.has_key?(:b) rescue false}
#=> {:b=>[:c, :d]}

for your specific example:

> Hash[*array][:a][:b]
#=> [:c, :d] 

Upvotes: 1

spickermann
spickermann

Reputation: 107107

Because it is an array (and not a hash) you can get an element by its index. In this example:

array[1]
#=> { :b => [:c, :d] }

Upvotes: 1

Related Questions