Ruby Expressions  Hot PDF Print E-mail
Tag it:
Delicious
Furl it!
Digg
NewsVine
Reddit
YahooMyWeb
Technorati
Articles Reviews Ruby
Written by Bogdan V   
Sunday, 03 December 2006
Article Index
Ruby Expressions  Hot
Backquotes Are Soft
Parallel Assignment
Conditional Execution
Common comparison operators
Loops
Variable Scope and Loops


{mos_sb_discuss:50}

So far we've been fairly cavalier in our use of expressions in Ruby. After all, a=b+c is pretty standard stuff. You could write a whole heap of Ruby code without reading any of this article.

But it wouldn't be as much fun ;-).

One of the first differences with Ruby is that anything that can reasonably return a value does: just about everything is an expression. What does this mean in practice?

Some obvious things include the ability to chain statements together.

a = b = c = 0     »     0

[ 3, 1, 7, 0 ].sort.reverse     »     [7, 3, 1, 0]

 


Perhaps less obvious, things that are normally statements in C or Java are expressions in Ruby. For example, the if and case statements both return the value of the last expression executed.

songType = if song.mp3Type == MP3::Jazz
             if song.written < Date.new(1935, 1, 1)
               Song::TradJazz
             else
               Song::Jazz
             end
           else
             Song::Other
           end


 rating = case votesCast
          when 0...10    then Rating::SkipThisOne
          when 10...50   then Rating::CouldDoBetter
          else                Rating::Rave
          end


Operator Expressions

Ruby has the basic set of operators (+, -, *, /, and so on) as well as a few surprises. A complete list of the operators, and their precedences.



In Ruby, many operators are actually method calls. When you write a*b+c you're actually asking the object referenced by a to execute the method ``*'', passing in the parameter b. You then ask the object that results from that calculation to execute ``+'', passing c as a parameter. This is exactly equivalent to writing

(a.*(b)).+(c)


Because everything is an object, and because you can redefine instance methods, you can always redefine basic arithmetic if you don't like the answers you're getting.

class Fixnum
  alias oldPlus +
  def +(other)
    oldPlus(other).succ
  end
end
1 + 2     »     4
a = 3
a += 4     »     8


More useful is the fact that classes that you write can participate in operator expressions just as if they were built-in objects. For example, we might want to be able to extract a number of seconds of music from the middle of a song. We could using the indexing operator ``[]'' to specify the music to be extracted.

class Song
  def [](fromTime, toTime)
    result = Song.new(self.title + " [extract]",
                      self.artist,
                      toTime - fromTime)
    result.setStartTime(fromTime)
    result
  end
end

This code fragment extends class Song with the method ``[]'', which takes two parameters (a start time and an end time). It returns a new song, with the music clipped to the given interval. We could then play the introduction to a song with code such as:

aSong[0, 0.15].play


Miscellaneous Expressions

As well as the obvious operator expressions and method calls, and the (perhaps) less obvious statement expressions (such as if and case), Ruby has a few more things that you can use in expressions.
Command Expansion

If you enclose a string in backquotes, or use the delimited form prefixed by %x, it will (by default) be executed as a command by your underlying operating system. The value of the expression is the standard output of that command. Newlines will not be stripped, so it is likely that the value you get back will have a trailing return or linefeed character.

`date`     »     "Sun Jun  9 00:08:26 CDT 2002\n"

`dir`.split[34]     »     "lib_singleton.tip"

%x{echo "Hello there"}     »     "Hello there\n"
You can use expression expansion and all the usual escape sequences in the command string.
for i in 0..3

  status = `dbmanager status id=#{i}`

  # ...

end


The exit status of the command is available in the global variable $?.



Last Updated ( Sunday, 11 February 2007 )
 
< Prev   Next >