2012-10-05 104 views
0

我有一个数组的Tile小号s用一个实例变量@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的对象?

回答

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'} 

下面是Array商务部:Ruby Array

+0

@БорисЦейтлин打印类型:这里是关于attr_reader的一些其他信息,你应该考虑阅读:http://stackoverflow.com/questions/5046831/why-use-rubys-attr-accessor-attr-reader-and-attr-writer – sunnyrjuneja

0

您可以覆盖在瓷砖类,返回从中型to_s,只是遍历你的阵列s通过调用<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}