问题描述:

Using Rails 4.2. I have the following:

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

Expected:

place.tap do |pl|

pl.name = "abc"

pl.administrative_area_level_1 = "Nevada"

pl.country = "United States"

end

The line pl.component.dig(:types).first = component[:long_name] doesn't work, for obvious reason.

What I want:

  • ability to assign values
  • only takes the first in types: administrative_area_level_1 and country

网友答案:
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
网友答案:

I use symbols instead:

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
相关阅读:
Top