我有一个ruby类,在其中一个方法中,它调用一个外部函数,并传入所有实例变量,并继续返回值。这是代码:
class MyClass
attr_accessor :name1
attr_accessor :name2
...
attr_accessor :namen
def inner_func():
all_vars = ???? # how to collect all my instance variables into a dict/Hash?
res = out_func(all_vars)
do_more_stuff(res)
end
end
问题是实例变量可能在子类中有所不同。我不能把它们称为他们的名字。那么,有没有办法做到这一点?或者我是否以错误的方式思考?
答案 0 :(得分:2)
您可以使用instance_variables
在阵列中收集它们。您将获得所有初始化的实例变量。
class MyClass
attr_accessor :name1
attr_accessor :name2
...
attr_accessor :namen
def inner_func():
all_vars = instance_variables
res = out_func(all_vars)
do_more_stuff(res)
end
end
答案 1 :(得分:0)
您可以在创建时跟踪所有访问者:
class Receiver
def work(arguments)
puts "Working with #{arguments.inspect}"
end
end
class MyClass
def self.attr_accessor(*arguments)
super
@__attribute_names__ ||= []
@__attribute_names__ += arguments
end
def self.attribute_names
@__attribute_names__
end
def self.inherited(base)
parent = self
base.class_eval do
@__attribute_names__ = parent.attribute_names
end
end
def attributes
self.class.attribute_names.each_with_object({}) do |attribute_name, result|
result[attribute_name] = public_send(attribute_name)
end
end
def work
Receiver.new.work(attributes)
end
attr_accessor :foo
attr_accessor :bar
end
class MySubclass < MyClass
attr_accessor :baz
end
用法
my_class = MyClass.new
my_class.foo = 123
my_class.bar = 234
my_class.work
# Working with {:foo=>123, :bar=>234}
my_subclass = MySubclass.new
my_subclass.foo = 123
my_subclass.bar = 234
my_subclass.baz = 345
my_subclass.work
# Working with {:foo=>123, :bar=>234, :baz=>345}