如何在Ruby类中公开所有属性

问题描述:

我有一个具有20多个属性的类,我希望它们中的每一个都是公共可读的,或者如果不是那么公开的。如何在Ruby类中公开所有属性

我似乎无法找到任何与此相关的数据。有谁能帮我在这里吗?

我想让所有这些都公开,而不必使用attr_reader输入所有20+个属性。

+1

你知道'在Ruby中attr_reader'方法?使用它像'attr_reader:x,:y,..' – 2015-04-01 08:48:55

+0

有20多个属性,我如何让它们全部公开,而不需要输入所有这些属性? – 2015-04-01 08:52:00

+1

那么,你想让Ruby阅读你的想法?我不明白。如果你不告诉它,那么Ruby应该知道这些属性的名字是什么? – 2015-04-01 11:17:32

您可以使用method_missing来做到这一点。每当有人试图调用一个你的班级不知道如何回应的方法时,就会调用method_missing

class Foo 

    def initialize 
    @a = 1 
    @b = 2 
    @c = 3 
    end 

    def respond_to_missing?(name) 
    super || has_attribute?(name) 
    end 

    def method_missing(name, *args) 
    if has_attribute?(name) 
     instance_variable_get("@#{name}") 
    else 
     super 
    end 
    end 

    private 

    def has_attribute?(name) 
    instance_variable_defined?("@#{name}") 
    end 

end 

这里是什么样子,当你使用它

foo = Foo.new 
p foo.a # => 1 
p foo.b # => 2 
p foo.c # => 3 
p foo.d # => method_missing error 

:为Ruby早于1.9.2:Override respond_to? instead of respond_to_missing?