我有一个数组的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