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

最終的に、すべてのユニットにディビジョンが割り当てられます。

4

2 に答える 2

1

かわいいワンライナー:

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

コードのバグは、何も見つからない場合にscan空の配列()を返し、空の配列が「真」であるということです。[]あなたが探している方法は、私のソリューションは、文字列検索結果(可能性があります)をユニットタイプにinclude?直接割り当てることによって、条件を完全にバイパスすることです。nil

于 2013-03-05T21:25:26.573 に答える
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
于 2013-03-04T21:49:08.477 に答える