A use for "foo = foo()" 
Author Message
 A use for "foo = foo()"

Folks coming to ruby might wonder why the parens are (sometimes)
optional when invoking a method. Here's one reason to like this feature.

I have a habit, sometimes, of writing code using repeated method calls
to access a value, rather than caching the result in a local variable.
Later, I try to tighten up my code using local vars. For example, I
start with:

   def foo      # or attr_reader :foo


   def bar

And later I insert

   def bar
     f = foo

and have to replace foo with f in the subsequent lines of bar.

But this extra work, and possible errors in the substitution, and
possible conflict with an existing f, can be avoided easily:

   def bar
     foo = foo()

The key is the extra "()" in "foo()", which I guess tells the parser
that it's a method call, not a local var. All subsequent invocations of
the #foo method become references to the local variable, "foo". You
don't have to change anything else, just insert one line, and you have
improved the efficiency of your program.

Of course, this won't affect method calls with an explicit receiver,
like "x.foo", or parens, like "foo()". So it's safer than doing a global
search and replace in your text editor, and you can override it where
you need to.

Wed, 27 Apr 2005 14:53:37 GMT  
 [ 1 post ] 

 Relevant Pages 

1. $foo == "" or [llength $foo] == 0

2. "import foo" and "from foo import bar"

3. "foo"

4. #pragma interface(C,"foo")

5. Dpulicating "class Foo:" in C

6. print "foo", without a space

7. "exception in foo.__del__() ignored" strangeness

8. if foo.__class__ == Foo: #in C?

9. foo.py vs. foo.pyc

10. Difference between $foo and [set foo]

11. eval $foo - does $foo get bytecompiled?

12. difference between ::foo::woof and foo::woof?


Powered by phpBB® Forum Software