[Courses] [Ruby] Lesson 0: Installing, References, and your first homework assignment

Katie Bechtold katie at hoteldetective.org
Wed Nov 9 09:37:57 EST 2005


> First, introduce yourself.  Do you know any other programming
> languages?  What do you like/not like about them?  Why are you
> interested in Ruby?  What are some things you'd like to learn to do?

Hi, I'm Katie!  Depending on the definition of "know", I know C,
C++, Java, Perl, Python, Fortran 77, Lisp, and Forth.  My favorites
among those are Python and Forth, both of which are flexible and
elegant, and both of which feature an interactive mode where you can
script "on the fly".  For me, the biggest sin of a programming
language is difficult readability, which is why I avoid Fortran like
the plague and haven't been able to appreciate Lisp as much as other
people.

I became interested in Ruby after reading Why's (Poignant) Guide to
Ruby[1] and hearing people rave about Ruby on Rails.  It looks like
Ruby's creator put a lot of thought into making life easier for
programmers.  I don't have any particular goals with respect to
Ruby; I'm just curious about it.

> Finally, look at the code.  Find a section of about 5-20 lines of
> code, and try to figure out what it does.

I found a Ruby application called rubyPod[2].  It's "a graphical
frontend for managing a iPod on Linux."  Here's a snippet from its
song.db:

class Song
  include Comparable

  ...

  def <=>(songb)
    if @pathSong==songb.pathSong
      0
    else
      #if the path is not the same then the songs cannot be equal
      if @nameArtist.downcase<songb.nameArtist.downcase
        -1
      elsif @nameArtist.downcase>songb.nameArtist.downcase
        1
      else
        if @nameAlbum.downcase<songb.nameAlbum.downcase
          -1
        elsif @nameAlbum.downcase>songb.nameAlbum.downcase
          1
        else
          @numSong.to_i<=>songb.numSong.to_i
        end
      end
    end
  end
end

What we have here is a method inside the Song class.  This method is
overloading Ruby's general comparison operator '<=>', which returns
-1, 0, or 1 depending on whether its left-hand operand is less then,
equal to, or greater than its right-hand operand.  Here, I think the
current Song object serves as the left-hand operand, and another
Song object denoted by 'songb' serves as the right-hand operand.

The first comparison in this function definition tests whether a
song is being compared to itself, to which it should be considered
equal.  The next test compares the lowercase version of the artist's
name (for case-insensitive sorting).  If those are equal, this
method compares the lowercase version of the album name.  If those
are also equal, it casts the songs' track numbers to integers and
compares them using the <=> operator for integers.


[1] http://poignantguide.net/ruby/
[2] http://rubypod.sourceforge.net/

-- 
Katie Bechtold         http://hoteldetective.org/




More information about the Courses mailing list