从散列调用块分配

时间:2017-01-17 16:25:39

标签: ruby-on-rails

使用Rails 4.2。我有以下内容:

place_details = {
  name: "abc",
  address_components: [
    { long_name: "Nevada", short_name: "NV", types: ["administrative_area_level_1", "political"] }, 
    { long_name: "United States", short_name: "US", types: ["country", "political"] }
  ]
}

place.tap do |pl|
  pl.name = place_details.dig(:name)
  place_details.dig(:address_components).each do |component|
    pl.component.dig(:types).first = component[:long_name]
  end
end

预期:

place.tap do |pl|
  pl.name = "abc"
  pl.administrative_area_level_1 = "Nevada"
  pl.country = "United States"
end

由于显而易见的原因,行pl.component.dig(:types).first = component[:long_name]不起作用。

我想要的是什么:

  • 分配值的能力
  • 只接受types中的第一个:administrative_area_level_1country

2 个答案:

答案 0 :(得分:0)

place_details.tap do |place|
  place.try(:[], :address_components).try(:each) do |address|
    place[address.try(:[], :types).try(:first)] = address.try(:[], :long_name)
  end
  place.delete(:address_components)
end

答案 1 :(得分:0)

我改为使用符号:

place.tap do |pl|
  pl[:name] = place_details.dig(:name)
  place_details.dig(:address_components).try(:each) do |component|
    pl[component.dig(:types)[0].to_sym] = component[:long_name]
  end
end