0

I am noob in ruby and have an array of hashes as per below. Say my array is @fruits_list:

[
    {:key_1=>15, :key_2=>"Apple"}, 
    {:key_1=>16, :key_2 =>"Orange"}, 
    {:key_1=>17, :key_2 =>"Cherry"}
]

What I am looking for is to join the names of the fruits. I did @fruits_list[:key_2].join('|')

and I am getting the error as "TypeError:no implicit conversion of Symbol into Integer"

Please suggest.

1 Answer 1

3

Use Array#collect first to collect names of fruits, then join them with a pipe | using Array#join

@fruits_list = [
                  {:key_1=>15, :key_2=>"Apple"}, 
                  {:key_1=>16, :key_2 =>"Orange"}, 
                  {:key_1=>17, :key_2 =>"Cherry"}
               ]
@fruits_list.collect { |hsh| hsh[:key_2] }.join("|")
# => "Apple|Orange|Cherry"

@fruits_list is an array of hash(s). Elements of an array can be accessed via the integer indexes only. But you tried to access it with a symbol :key_2, thus it raised an error as "TypeError:no implicit conversion of Symbol into Integer".

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

4 Comments

Thanks for helping. Looking at the error I understood what the issue was but wasn't able to get through the solution. Another method I tried was getting each object out of the array and then doing a join on it which was again incorrect because I was trying to join value of :key_2 of one object but the other object was not ready yet. Anyways this helped a lot!! Thanks!!
My requirement on this has changed a bit. I am now checking if the value is nil, then I wouldn't be including it in the list or collect. Eg: In the example in your reply, say {:key_1=>17, :key_2 => " "}; then I wouldn't include this in my list. My final list should be {"Apple" | "Orange"} and not {"Apple" | "Orange" | " "}. I tried this, @fruits_list.collect { |hsh| hsh[:key_2] unless hsh[:key_2].nil? }.join("|") but its still returning the nil value. What am I doing wrong here?
oh okay. I will do that. Since it was related to this, I added it here.

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.