Denis Denis - 1 month ago 8
Ruby Question

Ruby duplicate an object with modified params

I have a ruby object say

def initialize(args={})
@name = args[:name]
...
end

my_cat = Cat.new(name: 'Mittenz', age: 3, type: 'cheshire')


I need to duplicate it within another object but with an option to input a different parameter, somehting like this:

Class CatCopyist
def initialize(args={})
@my_cat = args[:cat] # my_cat object from above passed here
end

def copy_cat
another_cat = @my_cat.dup.merge(type: 'siamese')
return another_cat
end
...
end


I need help with blending the copied object with a new parameter.

Answer

You can use Object#instance_variable_set to override older variables.

class Cat
  attr_reader :name, :type, :age
  def initialize(args={})
    @name = args[:name]
    @age = args[:age]
    @type = args[:type]
  end

  def to_s
    "#{name} (#{type} - #{age})"
  end

  def dup(args={})
    new_cat = super()
    args.each do|var, value|
      new_cat.instance_variable_set(:"@#{var}", value)
    end
    new_cat
  end
end
mittenz = Cat.new(name: 'Mittenz', age: 3, type: 'cheshire')

puts mittenz
puts mittenz.dup(type: 'siamese')
#=> Mittenz (cheshire - 3)
#   Mittenz (siamese - 3)