0

I have an array s of Tiles with an instance variable @type:

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

How do I get each Tile's @type? How do I return only the objects with a particular @type?

sawa
  • 165,429
  • 45
  • 277
  • 381

2 Answers2

3

If you want to get an array containing each type attribute, you'll first need to create at least a reader for @type:

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

  end
end

Then use Array#map :

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

If you want to filter Tile object according to their @type value, Array#select is your friend :

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

Here's the doc for Array : Ruby Array

Anthony Alberto
  • 10,325
  • 3
  • 34
  • 38
  • @Борис Цейтлин: Here is some additional info on attr_reader that you should consider reading: http://stackoverflow.com/questions/5046831/why-use-rubys-attr-accessor-attr-reader-and-attr-writer – sunnyrjuneja Oct 05 '12 at 17:30
0

you can override to_s in your Tile class, return type from it and just iterate over your array s to print type by invoking <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}
saihgala
  • 5,724
  • 3
  • 34
  • 31