Ruby 如何循环一个条件,为不同的属性指定一个新值?
我试图使用:name属性中的文本在新的哈希数组中分配一个unit_类型 这是我的数据Ruby 如何循环一个条件,为不同的属性指定一个新值?,ruby,loops,where,Ruby,Loops,Where,我试图使用:name属性中的文本在新的哈希数组中分配一个unit_类型 这是我的数据 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
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
这适当地将“部门”指定为单位类型。
然而,我似乎不能分配任何其他东西,例如“旅”。
我应该使用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
我最终得到了分配给每个单位的除法。试试这个:
if unit_hash[:name].include?("Division")
u.unit_type = "Division"
elsif unit_hash[:name].include?("Brigade")
u.unit_type = "Brigade"
else
u.unit_type = nil
end
试试这个:
if unit_hash[:name].include?("Division")
u.unit_type = "Division"
elsif unit_hash[:name].include?("Brigade")
u.unit_type = "Brigade"
else
u.unit_type = nil
end
可爱的一行:
u.unit_type = unit_hash[:name][/Division|Brigade/]
代码中的错误是,scan
在找不到任何内容时返回一个空数组([]
),而空数组是“truthy”。您正在寻找的方法是include?
我的解决方案通过直接将字符串搜索结果(可以是nil
)分配给单元类型,完全绕过了条件。一行:
u.unit_type = unit_hash[:name][/Division|Brigade/]
代码中的错误是,
scan
在找不到任何内容时返回一个空数组([]
),而空数组是“truthy”。您正在寻找的方法是include?
我的解决方案通过直接将字符串搜索结果(可以是nil
)分配给单位类型来完全绕过条件?代替.scan,因为我将添加更多的单元类型。谢谢-这在我的下一个属性分配中证明是有用的。包括吗?代替.scan,因为我将要添加更多的单元类型。谢谢-这在我的下一个属性分配中被证明是有用的。我对该站点是全新的。看起来我需要至少15级的代表级别。我现在只有五个我对这个网站是全新的。看起来我需要至少15级的代表级别。我现在只有五个