how to override the new/initialize method for a struct?

J

jtprince

How do I make a custom initializer for a struct object? This is how I would expect it to be accomplished (but this does not work):

Dog = Struct.new:)bark, :bite) do
def initialize(*args)
super(*args)
bark = "really loud" unless bark
end
end

dd = Dog.new
p dd.bark # => should be "really loud" but is nil

So, structs have no initialize method... I tried some other approaches but no luck yet. Can anyone figure out how to do this?
 
G

Gary Wright

How do I make a custom initializer for a struct object? This is how I =
would expect it to be accomplished (but this does not work):
=20
Dog =3D Struct.new:)bark, :bite) do
def initialize(*args)
super(*args)
bark =3D "really loud" unless bark
end
end
=20
dd =3D Dog.new
p dd.bark # =3D> should be "really loud" but is nil
=20
So, structs have no initialize method... I tried some other =
approaches but no luck yet. Can anyone figure out how to do this?

I think your problem is just on one line. Make this change:
self.bark =3D "really loud" unless bark


Without that change you are assigning to a local variable and not to the =
'bark' attribute/instance variable.


Gary Wright
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,069
Latest member
SimplyleanKetoReviews

Latest Threads

Top