0

インスタンス変数を持つ s の配列sがあります。Tile@type

class Tile
  Types = ["l", "w", "r"]
  def initialize(type)
    @type = type
  end
end
s = []
20.times { s << Tile.new(Tile::Types.sample)}

それぞれを取得するにはどうすればよいTileです@typeか? 特定の を持つオブジェクトのみを返すにはどうすればよい@typeですか?

4

2 に答える 2

3

各型属性を含む配列を取得する場合は、最初に少なくとも次のリーダーを作成する必要があります@type

class Tile
  attr_reader :type
  Types = ["l", "w", "r"]
  def initialize(type)
    @type = type

  end
end

次に使用しますArray#map

type_attribute_array = s.map(&:type)
#or, in longer form
type_attribute_array = s.map{|t| t.type)

@type値に応じて Tile オブジェクトをフィルタリングする場合は、次のようにしArray#selectます。

filtered_type_array = s.select{|t| t.type == 'some_value'}

Ruby ArrayのドキュメントはArray次のとおりです。

于 2012-10-05T17:08:49.890 に答える
0

Tile クラスでオーバーライドし、そこから型を返し、配列を繰り返し処理して型を出力することができますto_ss<tile_object>.to_s

class Tile
  Types = ["l", "w", "r"]
  def initialize(type)
     @type = type
  end

  def to_s
     @type
  end
end

s = []
20.times { s << Tile.new(Tile::Types.sample)}
s.each {|tile| puts tile.to_s}
于 2012-10-05T17:13:11.443 に答える