我有一個數組的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
的對象?
我有一個數組的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
的對象?
如果你想獲得一個包含各類型屬性的數組,你需要先創建至少一個閱讀器@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
您可以覆蓋在瓷磚類,返回從中型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}
@БорисЦейтлин打印類型:這裏是關於attr_reader的一些其他信息,你應該考慮閱讀:http://stackoverflow.com/questions/5046831/why-use-rubys-attr-accessor-attr-reader-and-attr-writer – sunnyrjuneja