Ruby 如何列出一个对象的所有属性

tank_lei · April 02, 2013 · Last by tank_lei replied at April 12, 2013 · 10489 hits

别人封装的 gem 包,有没有方法可以查询一个对象的所有属性?就像方法 methods 一样。 比如有一对象 @test @test.methods 可以查询所有方法 有没有可以查看所有属性的呢?

instance_variables, 是不是这个

#1 楼 @chenge 打印出来 是这个: @attributes @service @loaded

@attributes 怎么弄呢?

#5 楼 @tank_lei 还需要什么,puts 不就显示了么

#5 楼 @tank_lei 实例变量都知道了,就可以根据具体的类型获取了赛

class A
  def initialize
    @a=0;@c=3
  end
  attr_accessor :a, :c, :b
end

a = A.new

ins_vars = a.instance_variables.map{|v|v.to_s[1..-1]}
methods = a.methods.map &:to_s
ins_vars & methods #attribute

用 pry 加个断点 ls 一下

表示是底层数据封装的原因!

You need to Sign in before reply, if you don't have an account, please Sign up first.