Reputation: 108
I have an array of parameters that are shared between two objects.
attributes = [:name, :category, :value]
The first object already has those parameters set. I would like to pass those same values onto the second object.
How do I do this?
My initial thought was to use:
attributes.each do |attribute|
@object_2.(attribute) = object_1.(attribute)
end
I also tried putting the attribute variable inside of "#{attribute}" but it still did not work.
I've tried a number of different solutions with no help, and Googling the answer for the past hour has not helped.
Some of the results seemed to suggest that I could accomplish what I was looking for with the send() method, but my attempts to use it did not help.
attributes.each do |attribute|
@object_2.send(attribute) = object_1.send(attribute)
end
If this question has been answered before (I could not find a solution by extensive searching) please point me towards a solution.
Thanks.
Upvotes: 0
Views: 103
Reputation: 118289
This is just a Hint about how this can also be done:
class Fred
def initialize(p1 = nil, p2 = nil)
@a, @b = p1, p2
end
def show
p [@a,@b]
end
end
f1 = Fred.new(10,11)
f2 = Fred.new
f1.instance_variables.each do |v|
f2.instance_variable_set(v,f1.instance_variable_get(v))
end
f2.show #=>[10, 11
You can also replace f1.instance_variables
by attributes
, if you want assignments to only some selected instance variables,not all.
Upvotes: 2
Reputation: 27207
You are probably close in your last attempt, assuming you have declared attr_accessor
for all the attributes in the respective class(es):
attributes.each do |attribute|
setter = (attribute.to_s + '=').to_sym
@object_2.send( setter, object_1.send( attribute ) )
end
The .to_sym
is optional, I just like to work with symbols when working with introspection.
There are also ways to do this without needing the instance variables exposed via attr_accessor
(it's not clear whether you need that)
Upvotes: 1
Reputation: 168199
attributes.each do |attribute|
@object_2.send("#{attribute}=", object_1.send(attribute))
end
Upvotes: 3