Ruby Quiz (A Trick Question)

December 9, 2007 Pivotal Labs

Here is a little Ruby trivium for you.

Type this into IRB:

def foo
  def bar
    1
  end
end

foo.bar
=> 1

Is this some magical lightweight object creation syntax so you can do cool method chaining? Let’s try another example:

def foo
  def foo
    1
  end
end

foo
=> nil

foo.foo
=> 1

So far so good. But now, type:

foo
=> 1

WTF? Is this a defect in Ruby?? Post your responses in the comments.

(Warning: this is a trick question)

About the Author

Biography

Previous
Making Ruby Look Like Smalltalk Haskell Erlang Ruby
Making Ruby Look Like Smalltalk Haskell Erlang Ruby

Inspired by Haskell Did you ever want to write Ruby Code like: x = 1 increment(x).by(6) Now you can: ...

Next
Get Rake to always show the error stack trace for your project
Get Rake to always show the error stack trace for your project

Tired of rake hiding your error stack trace? rake aborted! Build failed (See full trace by running task ...

×

Subscribe to our Newsletter

!
Thank you!
Error - something went wrong!