Checking for nil value inside collect function

喜欢而已 提交于 2019-12-12 02:19:19

问题


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?


回答1:


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.




回答2:


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"


来源:https://stackoverflow.com/questions/22716604/checking-for-nil-value-inside-collect-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!