From: clpoda@... Date: 2001-07-25T15:34:35+09:00 Subject: [ruby-talk:18510] Basic OO Tutorial, Ruby & Perl I have prepared a document called rubyboot, based on the perlboot man page (Beginner's Object-Oriented Tutorial). I added Ruby code to match the function of the Perl code in various sections of the original document. Rubyboot is now listed on the Ruby App Archive (under Documentation/Tutorial). The first draft is complete, and I'd appreciate any review comments to make it more accurate and correct. Find an html copy of the doc at: http://rubyboot.sourceforge.net One section that was a problem to me is listed below, along with my translation from Perl to Ruby. Please let me know if I have missed something important, or if there are more accurate ways to translate the Perl code to Ruby. This code is in the section titled 'Making a method work with either classes or instances'. ##### Start Perl code { package Animal; sub speak { my $either = shift; print $either->name, " goes ", $either->sound, "\n"; } sub name { my $either = shift; ref $either ? $$either # it's an instance, return name : "an unnamed $either"; # it's a class, return generic } sub named { my $class = shift; my $name = shift; bless \$name, $class; } } { package Horse; @ISA = qw(Animal); sub sound { "neigh" } } ## Now what happens if we invoke C on an instance? my $talking = Horse->named("Mr. Ed"); print Horse->name, "\n"; # prints "an unnamed Horse\n" print $talking->name, "\n"; # prints "Mr Ed.\n" $talking->speak; ## prints "Mr. Ed goes neigh" ##### Finish Perl code ##### Start Ruby code # One way to handle the case where no 'name' is provided class Animal def initialize(name) if name == "" @name = "an unnamed #{self.class} " else @name = name end end def speak print @name, " says ", sound, "\n" end end class Horse < Animal def sound; "neigh"; end end aHorse = Horse.new("") aHorse.speak talking = Horse.new("Mr. Ed") talking.speak ##### Finish Ruby Thanks for the help. clpoda