2012-10-05 191 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}