【问题标题】:Getting an object's instance variable获取对象的实例变量
【发布时间】:2012-10-05 17:00:39
【问题描述】:

我有一个 Tiles 的数组 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 的对象?

【问题讨论】:

    标签: ruby instance-variables accessor


    【解决方案1】:

    如果你想得到一个包含每个类型属性的数组,你首先需要为@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

    【讨论】:

    【解决方案2】:

    您可以在 Tile 类中覆盖 to_s,从中返回类型,然后通过调用 &lt;tile_object&gt;.to_s 遍历您的数组 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}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-08
      • 2015-08-19
      • 2021-03-23
      • 2012-01-21
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      相关资源
      最近更新 更多