如何获取通过attr_reader或attr_accessor定义的属性 [英] How to get attributes that were defined through attr_reader or attr_accessor

查看:39
本文介绍了如何获取通过attr_reader或attr_accessor定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个课程A

class A
  attr_accessor :x, :y

  def initialize(x,y)
    @x, @y = x, y
  end
end

如何获取xy属性而不知道它们的确切命名.

How can I get x and y attributes without knowing how exactly they were named.

例如

a = A.new(5,10)
a.attributes # => [5, 10]

推荐答案

使用内省,卢克!

class A
  attr_accessor :x, :y

  def initialize(*args)
    @x, @y = args
  end

  def attrs
    instance_variables.map{|ivar| instance_variable_get ivar}
  end
end

a = A.new(5,10)
a.x # => 5
a.y # => 10
a.attrs # => [5, 10]

这篇关于如何获取通过attr_reader或attr_accessor定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆