One of those interesting differences between python and ruby…

In fiddling with ruby, I noticed that the method names can be really interesting – rails (maybe others too, dunno) has some methods that look like:

object.stop?

which is typically used to return a boolean indicating wether or not “stop” is true. Ok, cool. Another interesting method call is

object.close

which appears to be identical to

object.close()

. That part really confused me, and I’m still not sure I have it completely clear.

In python

object.close

and

object.close()

are two very different things. The first is a reference to the instance method close – which you can pass around. The second is a specific invocation to the instance method. In ruby the parentheses appear to be optional if there are no arguments getting passed in to the function.

Update:
Dave Slorah pointed out that the parantheses option thing extends beyond just the no-argument methods – it applies all over the place!

irb(main):010:0> def foo(bar,baz)
irb(main):011:1>   puts bar
irb(main):012:1>   puts baz
irb(main):013:1> end
=> nil
irb(main):014:0> foo "hello", "world"
hello
world

My first thought it “Wow – that’s almost Objective-C like…”

Published by heckj

Developer, author, and life-long student. Writes online at https://rhonabwy.com/.

2 thoughts on “One of those interesting differences between python and ruby…

  1. You are correct — Ruby offers the lack of parentheses as shorthand for invocation of a parameter-less method.

    While convenient, it makes for treating methods as first class objects in Ruby considerably less convenient and, thus, you don’t see methods-as-objects used often in Ruby.

    Sad, because it enables some pretty simple, straightforward, and very powerful design patterns.

    Instead, Ruby encourages the use of blocks to encapsulate a callable. Powerful in and of itself and enables a different set of patterns not possible with Python’s lambda.

    Like

  2. I haven’t yet grokked the blocks thing in ruby either – but it sort of appeals to me with what it enables. I haven’t yet gotten used to being able to read that code right through and have a gut sense of what it’s supposed to be doing/mean as yet.

    Like

Comments are closed.

%d bloggers like this: