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.

tech_human
  • 6,592
  • 16
  • 65
  • 107

1 Answers1

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".

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • 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!! – tech_human Feb 19 '14 at 20:26
  • 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? – tech_human Mar 28 '14 at 15:01
  • oh okay. I will do that. Since it was related to this, I added it here. – tech_human Mar 28 '14 at 15:05
  • I created it here - http://stackoverflow.com/questions/22716604/checking-for-nil-value-inside-collect-function – tech_human Mar 28 '14 at 15:12