0

I 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 =>" "}
]

I want to join the values in the hash using a '|'; but my final output should not contain the nil value. I connect it using:

@fruits_list.collect { |hsh| hsh[:key_2] }.join("|")

But this adds nil in my output, so my final output has 3 items {"Apple" | "Orange" | " "}. I want 2 items in my list and would like to eliminate the nil value, so my final output should look like {"Apple" | "Orange"}.

I tried: @fruits_list.collect { |hsh| hsh[:key_2] unless hsh[:key_2].nil? }.join("|") but even this returns me 3 items in the final output. What am I doing wrong or how can I eliminate the nil value?

tech_human
  • 6,592
  • 16
  • 65
  • 107

2 Answers2

3

You can filter on non-blank values using:

a.collect{ |h| h[:key_2] }.select(&:present?).join('|')

The present? method returns true only if the thing is sufficiently "non-blank", that is empty string, string composed of spaces, empty array, empty hash are all considered blank.

tadman
  • 208,517
  • 23
  • 234
  • 262
1
a = [
    {:key_1=>15, :key_2=>"Apple"}, 
    {:key_1=>16, :key_2 =>"Orange"}, 
    {:key_1=>17, :key_2 =>" "}
]

a.collect{ |hsh| hsh[:key_2] unless hsh[:key_2] =~ /\s+/}.compact.join("|")

#=> "Apple|Orange"
Bala
  • 11,068
  • 19
  • 67
  • 120