[英]Ruby modify hash value if value array
我有一個像這樣的紅寶石哈希:
hash = {properties: [13], attributes: [11, 15, 15], places: [66]}
我想將我的哈希值轉換為:
hash = {properties: 13, attributes: [11, 15], places: 66}
數組長度大於1的所有值都保持原樣(數組),所有其他值均排在第一位。 嘗試了幾次ifs,沒有找到我想要的方式
hash.map{ |k,v| { k => v.uniq } }.reduce(&:merge)
這是我的做法:
Hash[hash.map { |k ,v| [k, v.size > 1 ? v.uniq : v.first] }]
# => {:properties=>13, :attributes=>[11, 15], :places=>66}
# or
hash.map { |k ,v| [k, v.size > 1 ? v.uniq : v.first] }.to_h
# => {:properties=>13, :attributes=>[11, 15], :places=>66}
def convert(h) Hash[h.map {|k,v| [k, v.size == 1 ? v.first : v.uniq]}] end convert(hash) # => {:properties=>13, :attributes=>[11, 15], :places=>66}
這是另一種方式:
hash.merge(hash) { |*_, v| (v.size==1) ? v.first : v.uniq }
=> {:properties=>13, :attributes=>[11, 15], :places=>66}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.