我遍历所有汽车及其支持的属性(每辆汽车的许多属性)来创建这样的结构,我该如何以动态方式执行此操作。
cars = {
"honda" => {'color' => 'blue', 'type' => 'sedan'}.
"nissan" => {'color' => 'yellow', 'type' => 'sports'}.
...
}
cars.each do |car|
car_attrs = ...
car_attrs.each do |attr|
??? How to construct the above structure
end
end
答案 0 :(得分:2)
你的问题不是很清楚......但我想这就是你想要的:
cars = {}
options = {}
options['color'] = 'blue'
...
cars['honda'] = options
那是你在找什么?
答案 1 :(得分:2)
听起来你可能想要一种创建二维哈希的方法,而不必显式创建每个子哈希。实现此目的的一种方法是指定为散列键创建的默认对象。
# When we create the cars hash, we tell it to create a new Hash
# for undefined keys
cars = Hash.new { |hash, key| hash[key] = Hash.new }
# We can then assign values two-levels deep as follows
cars["honda"]["color"] = "blue"
cars["honda"]["type"] = "sedan"
cars["nissan"]["color"] = "yellow"
cars["nissan"]["type"] = "sports"
# But be careful not to check for nil using the [] operator
# because a default hash is now created when using it
puts "Found a Toyota" if cars["toyota"]
# The correct way to check would be
puts "Really found a Toyota" if cars.has_key? "toyota"
许多客户端库假定[]运算符返回nil默认值,因此在使用此解决方案之前,请确保其他代码不依赖于该行为。祝你好运!
答案 2 :(得分:0)
假设您使用类似于ActiveRecord的东西(但如果不是,则很容易修改):
cars_info = Hash[cars.map { |car| [car.name, car.attributes] }