2013-03-04 27 views
1

我正在嘗試使用: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 

我最終得到Divison分配給每個單位。

回答

1

可愛的一行:

u.unit_type = unit_hash[:name][/Division|Brigade/] 

在你的代碼中的錯誤是scan返回一個空數組([]),當它沒有找到任何東西,一個空陣列是「真理」。您正在尋找的方法是include?我的解決方案完全通過直接將字符串搜索結果(可以是nil)分配給單位類型來繞過條件。

+0

我去.include?代替.scan,因爲我將添加更多單元類型。 – user2130052 2013-03-06 16:46:17

+0

謝謝 - 這在我的下一個屬性分配中證明是有用的 – user2130052 2013-03-06 16:47:30

0

試試這個:

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 
+1

和BAM - 工作。 – user2130052 2013-03-06 16:44:11

+0

很高興我能幫到你。 – BlackHatSamurai 2013-03-06 17:03:40

+0

如果你喜歡這個答案,你可以upvote /接受它。 – BlackHatSamurai 2013-03-06 17:11:18

相關問題