SameShirtEveryDay.com

Personal blog of the one called Alex Gorbatchev, from Toronto, Canada.

Learning Ruby: A little trick to overriding parameterless constructors

Posted on September 14th, 2007 by Alex Gorbatchev. In Ruby. 2 comments!

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.

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 comments.

  1. Thanks for this post! This totally got me and I was stumped till I found your post

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> , rel="nofollow" in use - no link dropping, no keywords or domains as names; do not spam, and do not advertise!

home
Subscribe to this blog Follow me on Twitter My bookmarks on Delicious My photography on Flickr