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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Борис Цейтлин: Here is some additional info on attr_reader that you should consider reading: stackoverflow.com/questions/5046831/…
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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.