From: Todd Benson Date: 2007-07-24T22:04:49+09:00 Subject: Re: Ruby Basics On 7/24/07, Ralph Grothe wrote: > Hello, > That's where my first question arose. > Being used to the Perl debugger for similar experiments like with irb, > the former at least offers, albeit moderate, history amenities (viz. > !cmd#, to repeat cmd No. #) > I would have expected irb to offer some readline and thus command > history support (I am a lousy typer)? It should. Did you compile with readline (you need to have lib-readline of course). > Then while reading the code examples in the PickAxe I was a little > bewildered > how the authors were merrily extending their sample classes by simply > redifinig some method to add functionality without, as I would have > expected, > first sublassing the class and then overriding single methods. > > Instead it went like this > > E.g. > > class Noise > def moo > # some implementation > end > end > > # more paragraphs of text > # and then taking up again > > class Noise > def moo > # deviating implementation from first definition > end > end > > # and so forth > > > I this valid (and recommnded) Ruby, or were they just > sweeping former stuff under the carpet to keep the sample code terse? > Similarily, I was puzzled that it seems to be possible to > again extend base classes like Array without being required to subclass > and override, instead doing something like > > class Array > def my_super_sort > # implementation > end > end > > Is this really all that easy? Yes, but as in all easy things, there are caveats. You can 'open' up any class, and, in fact, any object whenever you want. irb> a = "hello" => "hello" irb> b = "hajimemashite" => "hajimemashite" irb> a.class => String irb> b.class => String irb> class String; def welcome_f; puts self + ", welcome to f method!"; end; end => nil irb> a.welcome_f hello, welcome to f method! => nil irb> b.welcome_f hajimemashite, welcome to f method! irb> def a.welcome_g; puts self + ", welcome to g method!"; end; end => nil irb> a.welcome_g hello, welcome to g method! => nil irb> b.welcome_g NoMethodError: undefined method 'g' for "hajimemashite":String The welcome_g method for the object a is called a singleton method. It applies only to a. There are obvious risks in opening up core classes (like String), especially if you modify them instead of just adding to them. Even adding to classes after the fact is somewhat dangerous because of possible clashes with gems that you use, or sometimes even with your own code! > As for style, shouldn't Ruby class definitions just as one > class-end block go into a single file instead of these break ups? That's almost certainly up to you. hth a little, Todd