0

In Ruby, I have a list of property names like the following:

names = [
  :foo,
  #...
]

I'd like to iterate through the list and, using reflection, perform conditional assignment on the property name. So, for example, rather than this, which doesn't use reflection:

self.foo ||= 0

I'd like something like something like this:

for name in names
   #use local variable "name" to perform assignment using reflection 
end

How can I achieve this using Ruby reflection?

4

2 に答える 2

2
names.each { |name| self.instance_variable_set("@#{name}", 0) }

will probably be a first approximation for what you need to do.

于 2013-03-25T12:35:26.173 に答える
2
foo.bar ||= baz

is roughly equivalent to

foo.bar || foo.bar = baz

It's not quite the same, but close enough for your purpose, I think. So,

names.each do |name| send(name) || send(:"#{name}=", 0) end

should do what you want. That is of course equivalent to

names.each do |name| send(:"#{name}=", 0) if send(name) end

which might be a little easier to understand.

于 2013-03-25T14:02:39.693 に答える