如何合并单个哈希的值?

时间:2017-07-25 10:16:22

标签: ruby hash

有没有办法合并单个哈希的值?

示例:

address = { 
    "apartment" => "1",
    "building" => "Lido House",
    "house_number" => "20",
    "street_name" => "Mount Park Road",
    "city" => "Greenfield",
    "county" => nil,
    "post_code" => "WD1 8DC"
}

我们能得到一个看起来像这样的结果吗?

1 Lido House,
20 Mount Park Road,
Greenfield,
WD1 8DC

address.compact将删除等于nil的值,但如果在方法中包含字符串插值并且您想要排除某些地址的nil值并将其包含在其他没有逗号的其他地址中,该怎么办?

def address(hash)
    hash.compact
    puts "#{hash["apartment"]} #{hash["building"]}, \n#{hash["house_number"]} #{hash["street_name"]}, \n#{hash["city"]}, \n#{hash["county"]}, \n#{hash["post_code"]}"
end

2 个答案:

答案 0 :(得分:0)

您需要在字符串中加入值:

"#{address['house_number']} #{address['street_name']},\n#{address['city']},\n#{address['post_code']}"

您还可以通过将其作为辅助方法并使用HEREDOC来改进格式:

def formatted_address(address)
  <<~ADDRESS
    #{address['house_number']} #{address['street_name']},
    #{address['city']},
    #{address['post_code']}
  ADDRESS
end

用法:

address = { 
  "house_number" => 20,
  "street_name" => "Mount Park Road",
  "city" => "Greenfield",
  "post_code" => "WD1 8DC"
}

puts formatted_address(address)
  # => 20 Mount Park Road,
  #    Greenfield,
  #    WD1 8DC

答案 1 :(得分:0)

使用string formats

"%{house_number} %{street_name},\n%{city},\n%{post_code}" % address