Learning Ruby: A little trick to overriding parameterless constructors
After almost 8 months of working with Ruby, it still offers something new every day. Here’s a tricky part about overriding a constructor without any arguments:
class A
def initialize
@foo = 123
end
end
class B < A
def initialize(special_argument)
# This call will result in "wrong number of arguments (1 for 0)"
# exception because Ruby automatically passes all arguments.
super
# ... the same as ...
super(*args)
# Special case of calling super class' constructor without
# argument - you MUST include parentheses to indicate
# that you aren't passing any arguments.
super()
end
end
Obviously, I would’ve known that if I read the manual, but it would be too easy.
2 comments.
Thanks for this post! This totally got me and I was stumped till I found your post
Leave a Reply