1

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]).

1
  • Why don't you want to index an in the usual manner? Are you trying to search the array for an element that is a hash with a :b key? Commented Aug 5, 2018 at 16:47

3 Answers 3

1

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] }
Sign up to request clarification or add additional context in comments.

1 Comment

thank you. but I want to get it with key not index how can i do that?
1

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] 

Comments

0

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]

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.