在哈希数组中查找第一个值

时间:2015-03-26 06:03:45

标签: ruby arrays hash

我有以下数组。

[
  {"title"=>"un", "link"=>nil, "description"=>""},
  {"title"=>"deux", "link"=>"https://apple.com", "description"=>"Products"},
  {"title"=>"three", "link"=>"http://www.amazon.com", "description"=>"Welcome"},
  {"title"=>"four", "link"=>"https://apple.com", "description"=>"iPad"},
]

我想删除链接为nil或为空的哈希值,返回一个链接数组来获取:

["https://apple.com", "http://amazon"]

不确定如何删除哈希值并仅获取唯一链接。

5 个答案:

答案 0 :(得分:3)

删除空("")和nil值:

arr.map { |a| a["link"] }.reject(&:blank?).uniq

正如@Arup指出blank在Rails中,纯Ruby解决方案将是:

arr.map { |a| a["link"] }.reject{|e| e == "" || e == nil}.uniq

答案 1 :(得分:2)

请尝试以下代码

arr.map {|o| o['link'] }.reject { |e| e.to_s.empty? }.uniq

答案 2 :(得分:1)

<强>解决方案:

a = [
{"title"=>"un", "link"=>nil, "description"=>""},
{"title"=>"deux", "link"=>"https://apple.com", "description"=>"Products"},
{"title"=>"three", "link"=>"http://www.amazon.com", "description"=>"Welcome"},
{"title"=>"four", "link"=>"https://apple.com", "description"=>"iPad"},
]
a.map{|data| data["link"] }.reject(&:blank?).uniq

<强>解释

a是哈希数组

Map将遍历数组中的每个哈希,并使用&#34;链接创建一个新数组&#34;值。如果原始哈希没有链接密钥,它将在新数组中创建一个nil值。

Example result after map: 
[nil, "https://apple.com", "https://www.amazon.com", "https://apple.com"]

拒绝然后调用rails active支持方法空白?在数组中的每个项目,如果是空白?返回true返回一个没有值的新数组:

[nil.blank?, "https://apple.com".blank?, "https://www.amazon.com".blank?, "https://apple.com".blank?]
Result:    
["https://apple.com", "https://www.amazon.com", "https://apple.com"]

Uniq然后生成一个没有重复的数组(另一种方法是使用ruby集)

["https://apple.com", "https://www.amazon.com"]

答案 3 :(得分:0)

你可以做:

 arr.map {|o| o['link'] }.compact.uniq

compact删除所有niluniq返回唯一值。

答案 4 :(得分:0)

您可以使用Enumerable#each_with_object

array.each_with_object([]) do |h, a|
  a << h['link'] unless h['link'].nil? || h['link'].empty?
end.uniq
# => ["https://apple.com", "http://www.amazon.com"]