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

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?

okay, this works:

Dog = Struct.new(:bark, :bite)

class Dog
class << self
alias_method :old_new, :new
def new(*args)
obj = old_new(*args)
obj.bark = ‘really loud’
obj
end
end
end

dd = Dog.new
p dd.bark # => should be “really loud”

More concisely:

Dog = Struct.new(:bark, :bite) do
class << self
alias_method :old_new, :new
def new(*args)
obj = old_new(*args)
obj.bark = ‘really loud’
obj
end
end
end

On Feb 25, 2011, at 1:51 PM, jtprince wrote:

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?

I think your problem is just on one line. Make this change:

self.bark = “really loud” unless bark

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

Gary W.

You are right, this works when the self is explicit on the assignment.
It’s also very POLS. I like it!

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

Thanks for the heads up!