user2471254
user2471254

Reputation: 1

Create Object from Subclass-Object

say I've got 2 Classes:

Class Foo
    attr_accessor :bar
end

Class Baz < Foo
end

I'm creating an Instance of Foo and then want to have an Instance of Baz with the Data of the Foo Instance in it:

f = Foo.new(:bar => "Hi World")

# Doesnt work?
b = Baz.new(f)

How to do it?

Upvotes: 0

Views: 120

Answers (1)

Stefan
Stefan

Reputation: 114218

an instance of Baz with the data of the Foo instance in it

Since your constructor already accepts attributes as a hash, you could create a method to return Foo's attributes as a hash:

class Foo
  attr_accessor :bar

  def initialize(attributes={})
    @bar = attributes[:bar]
  end

  def attributes
    {:bar => bar}
  end
end

class Baz < Foo
end

Now you can create a Baz instance from these attributes:

f = Foo.new(:bar => "Hi World")   #=> #<Foo:0x007fd09a8614c0 @bar="Hi World">
f.attributes                      #=> {:bar=>"Hi World"}

b = Baz.new(f.attributes)         #=> #<Baz:0x007fd09a861268 @bar="Hi World">

Upvotes: 2

Related Questions