我正在尝试使用 :name 属性中的文本在新的哈希数组中分配 unit_type 。
这是我的数据
class Unit
attr_accessor :name
attr_accessor :imported_id
attr_accessor :country
attr_accessor :unit_type
raw_stuff = [{:old_id=>576, :name=>"16th Armored Division (USA) "}, {:old_id=>578, :name=>"20th Armored Division (USA)"}, {:old_id=>759, :name=>"27th Armoured Brigade (UK)"}, {:old_id=>760, :name=>"- 13th/18th Royal Hussars"}, {:old_id=>761, :name=>"- East Riding of Yorkshire Yeomanry "}, {:old_id=>762, :name=>"- Staffordshire Yeomanry "}, {:old_id=>769, :name=>"A I R B O R N E "}, {:old_id=>594, :name=>"1st Airborne Division (UK)"}, {:old_id=>421, :name=>"6th Airborne Division (UK)"}]
units = []
raw_stuff.each do |unit_hash|
u = Unit.new
u.name = unit_hash[:name].sub("-","").lstrip
u.unit_type = unit_hash[:name].scan("Division")
puts u.unit_type
puts u.name
end
end
这适当地将“除法”分配为 unit_type。但是我似乎不能分配其他任何东西,例如“旅”。我应该使用 if 或 where 条件吗?
When I use the following code:
raw_stuff.each do |unit_hash|
u = Unit.new
u.name = unit_hash[:name].sub("-","").lstrip
if unit_hash[:name].scan("Division")
u.unit_type = "Division"
elsif unit_hash[:name].scan("Brigade")
u.unit_hash = "Brigade"
else
u.unit_hash = nil
end
puts u.unit_type
puts u.name
end
我最终将分部分配到每个单位。