Ruby duplicate an object with modified params -
i have ruby object say
def initialize(args={}) @name = args[:name] ... end my_cat = cat.new(name: 'mittenz', age: 3, type: 'cheshire')
i need duplicate within object option input different parameter, somehting this:
class catcopyist def initialize(args={}) @my_cat = args[:cat] # my_cat object above passed here end def copy_cat another_cat = @my_cat.dup.merge(type: 'siamese') return another_cat end ... end
i need blending copied object new parameter.
you can use object#instance_variable_set 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)
Comments
Post a Comment