[GD-General] RE: Ruby
Brought to you by:
vexxed72
From: Jesse J. <jes...@mi...> - 2001-12-28 03:59:30
|
At 8:55 PM -0500 12/27/01, Patrick M Doane wrote: >On Thu, 27 Dec 2001, Jesse Jones wrote: > >> Not necessarily. For example, Ruby allows you to stick executable >> code outside method definitions so you can do stuff like this: >> >> if want_foo_method() # add foo() to our class if it's OK >> def foo(arg1, arg2) # the foo method >> # code goes here >> end >> end >> >> I'm no Ruby guru yet, but it wouldn't surprise me if you could even >> do things like use a loop instead of an if statement and add a bunch >> of similar foo1, foo2, etc methods. > >TCL has similar functionality which can be very confusing because it >doesn't follow expected scoping rules. Procedures declared within >procedures exist within the global namespace rather than locally as one >might expect. > >I seem to recall that Ruby was a little smarter about this, building >closures to functions as appropriate. Ruby doesn't have free functions or nested functions. However you can define a method outside a class. If you do this the method is automatically added as a private method to the root object class which, for all intents and purposes, makes it a global function. Ruby also has closures which are sort of like in-line nested functions that retain their context. The Ruby library classes make heavy use of these. Here's an example: def accumulate(collection, value = 0) collection.each {|entry| value += entry} return value end The stuff between the braces is the closure. The each() method calls the closure for each item in the collection passing into the closure the current item (referenced as entry within the closure). BTW one of the really cool things about Ruby is that classes aren't closed. For example, I was just bitching about std::string not having a back() method like *every* other sequential container in the standard library. In Ruby this would be trivial to fix. In C++ I have to use a free function or something gross like *(str.end() - 1). -- Jesse |