Cover | Table of Contents | Colophon
$ which ruby
/usr/local/bin/ruby
$ ruby -v
$ ruby --version
ruby 1.8.6 (2007-03-13 patchlevel 0) [powerpc-darwin8.9.0]
puts "Hello, Matz!"
Hello, Matz! on your screen, followed by a newline character.;) if you want, just like in C or Java, but you sure don't have to: a newline will do fine. (Most Ruby programmers don't use ; except when writing multiple statements on one line.)$ irb -v
irb 0.9.5(05/04/13)
irb(main):001:0> puts "Hello, Matz! " Hello, Matz! => nil
nil, set off by => in the output of irb, is a value returned by the method puts. nil has a special meaning in Ruby. It denotes empty and always means false.puts prints out the string Hello, Matz!, followed by a newline character.LF (linefeed) character; on Microsoft Windows, it's CR+LF (a carriage return character followed by a linefeed).Hello, Matz! is assigned to the name hi and printed by puts:irb(main):002:0> hi = "Hello, Matz!" => "Hello, Matz! " irb(main):003:0> puts hi Hello, Matz! => nil
hi three times:irb(main):004:0> puts hi * 3 Hello, Matz! Hello, Matz! Hello, Matz! => nil
irb(main):006:0> 10 + 10 => 20 irb(main):007:0> 4 * 5 => 20 irb(main):008:0> 100 / 5 => 20 irb(main):009:0> 50 - 30 => 20 irb(main):010:0> 80 % 60 => 20
configure and make. We'll take advantage of them here as we install a new version of Ruby on Tiger (these steps could apply to a Linux installation as well).-bash: ./matz.rb: Permission denied
chmod command by typing:chmod 755 matz.rb
755 makes the control list read rwxr-xr-x (where r means read, w write, and x execute). This means that the file is readable and executable by everyone (owner, group, and others, in that order), but writable only by the owner. To find out more about chmod, type man chmod at a shell prompt.#!), which allows the program to execute by merely invoking its name in a shell on Unix/Linux systems. However, you can achieve a similar effect to shebang by creating a file type association with the assoc and ftype commands on Windows.assoc command:C:\Ruby Code>assoc .rb
File association not found for extension .rbC:\Ruby Code>assoc .rb=rbFileC:\Ruby Code>assoc .rb
.rb=rbFileC:\Ruby Code>ftype rbfile
File type 'rbfile' not found or no open command associated with it.C:\Ruby Code>ftype rbfile="C:\Program Files\Ruby\bin\ruby.exe" "%1" %*%1 is a substitution variable for the file you want to run, and %* accepts all other parameters that may appear on the command line. Test it:C:\Ruby Code>ftype rbfile
rbfile="C:\Program Files\Ruby\bin\ruby.exe" "%1" %*PATHEXT environment variable. Is it there already?C:\Ruby Code>set PATHEXT PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.tcl
C:\Ruby Code>set PATHEXT=.rb;%PATHEXT%C:\Ruby Code>set PATHEXT
PATHEXT=.rb;.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.tclC:\Ruby Code>matz
Hello, Matz!Object class and the Kernel module, reserved words (keywords), comments, variables, methods, and so forth. Most topics will be dealt with elsewhere in the book in more detail. Some topics merit entire chapters, others only sections (found in ). I'll always tell you where else to look for more information on a topic. This book's most detailed discussions on methods and blocks are found in this chapter.new method, this blueprint can be assigned to a variable or become instantiated, and thereby become an object. In Ruby, almost everything is an object; in fact, everything that Ruby can bind to a variable name is an object.Hello and Goodbye. You'll find this program in the archive of Ruby programs that comes with this book (download it from http://www.oreilly.com/catalog/learningruby). Run this program at a shell or command prompt, in the directory where the archive was installed. If a code example is not in a file, you can type that code in irb to see for yourself what it does. I encourage you to run as much code as you dare.new method, this blueprint can be assigned to a variable or become instantiated, and thereby become an object. In Ruby, almost everything is an object; in fact, everything that Ruby can bind to a variable name is an object.Hello and Goodbye. You'll find this program in the archive of Ruby programs that comes with this book (download it from http://www.oreilly.com/catalog/learningruby). Run this program at a shell or command prompt, in the directory where the archive was installed. If a code example is not in a file, you can type that code in irb to see for yourself what it does. I encourage you to run as much code as you dare.class Hello def howdy greeting = "Hello, Matz!" puts greeting end end class Goodbye < Hello def solong farewell = "Goodbye, Matz." puts farewell end end friendly = Goodbye.new friendly.howdy friendly.solong
$ friendly.rb Hello, Matz! Goodbye, Matz.
Reserved word | Description |
|---|---|
BEGIN | Code, enclosed in { and }, to run before the program runs. |
END | Code, enclosed in { and }, to run when the program ends. |
alias | Creates an alias for an existing method, operator, or global variable. |
and | Logical operator; same as && except and has lower precedence. (Compare with or.) |
begin | Begins a code block or group of statements; closes with end. |
break | Terminates a while or until loop or a method inside a block. |
\case | Compares an expression with a matching when clause; closes with end. (See when.) |
class | Defines a class; closes with end. |
def | Defines a method; closes with end. |
defined? | A special operator that determines if a variable, method, super method, or block exists. |
do | Begins a block and executes code in that block; closes with end. |
else | Executes following code if previous conditional, in if, elsif, unless, or when, is not true. |
elsif | Executes following code if previous conditional, in if or elsif, is not true. |
end | Ends a code block (group of statements) starting with begin, def, do, if, etc. |
ensure | Always executes at block termination; use after last rescue. |
false | Logical or Boolean false, instance of FalseClass. (See true.) |
for | Begins a for loop; used with in. |
if | Executes code block if conditional statement is true. Closes with end. (Compare with unless, until.) |
in | Used with for loop. (See for.) |
module | Defines a module; closes with end. |
next | Jumps before a loop's conditional. (Compare with redo.) |
nil | Empty, uninitialized variable, or invalid, but not the same as zero; object of NilClass. |
not | Logical operator; same as !. |
or | Logical operator; same as || except or has lower precedence. (Compare with and.) |
redo | Jumps after a loop's conditional. (Compare with |
#) can be at the beginning of a line:# I am a comment. Just ignore me.
name = "Floydene Wallup" # ain't that a name to beat all
# This is a comment. # This is a comment, too. # This is a comment, too. # I said that already.
=begin/=end:=begin This is a comment. This is a comment, too. This is a comment, too. I said that already. =end
x is assigned the value 100 by the equals sign.x = 100
x holds the value 100. But, hey, what type is it? Looks like an integer to me—how about you? And what does Ruby think?int) on the left:int months = 12; int year = 2007;
months = 12 year = 2007
x, months, and year are clearly integers, but you didn't have to give them a type because Ruby does that for you, automatically. It's called dynamic or duck typing.x—that is, whether it is an integer—with the kind_of? method (this method is from the Object class).x.kind_of? Integer # => true
x behaves like an integer! As a matter of fact, it is an instance of the Fixnum class, which inherits the Integer class.x.class # => Fixnum
x from an integer to a floating point with the to_f method from the Fixnum class (it is inherited by other classes, too).x.to_f # => 100.0
thoreau = "If a man does not keep pace with his companions, perhaps it is because he hears a different drummer."
String methods, you can access and manipulate the string thoreau. For example, you can retrieve part of a string with the [] method, using a range. Let's grab characters 37 through 46:thoreau[37..46] # => "companions"
thoreau[-8..-2] # => "drummer"
chr method), separating each character with a slash:thoreau.each_byte do |c| print c.chr, "/" end # => I/f/ /a/ /m/a/n/ /d/o/e/s/ /n/o/t/ /k/e/e/p/ /p/a/c/e/ /w/i/t/h/ /h/i/s/ /c/o/m/p/a/n/i/o/n/s/,/ /p/e/r/h/a/p/s/ /i/t/ /i/s/ /b/e/c/a/u/s/e/ /h/e/ /h/e/a/r/s/ /a/ /d/i/f/f/e/r/e/n/t/ /d/r/u/m/m/e/r/./
$KCODE variable to 'u' (for UTF-8), 'e' (for EUC), 's' (for SJIS), or 'a' or 'n' (for ASCII or NONE).chr method converts a character code (which each_byte produces) into an actual character. You should also know about the opposite method—the ? operator, which returns a character code from a character. I'll demonstrate that with 1001, a positive integer, is an instance of the Fixnum class, which is a child class of Integer, which is a child class of Numeric. The number 1001.0, a floating point value, is an instance of the Float class, which is also a child class of Numeric. ( shows the relationships between these classes.)irb(main):001:0> 3+ 4 # add => 7 irb(main):002:0> 7 - 3 # subtract => 4 irb(main):003:0> 3 * 4 # multiply => 12 irb(main):004:0> 12 / 4 # divide => 3 irb(main):005:0> 12**2 # raise to a power (exponent) => 144 irb(main):006:0> 12 % 7 # modulo (remainder) => 5
irb(main):007:0> x= 12 # assignment => 12 irb(main):008:0> x += 1 # abbreviated assignment add => 13 irb(main):009:0> x -= 1 # abbreviated assignment subtract => 12 irb(main):010:0> x *= 2 # abbreviated assignment multiply => 24 irb(main):011:0> x /= 2 # abbreviated assignment divide => 12
Math module that provides all kinds of math functions (in the form of class methods), like square root, cosine, tangent, and so forth. Here is an example call to the class method sqrt from the Math module:irb(main):012:0> Math.sqrt(16) => 4.0
Rational for doing fractions. You'll learn much more about numbers and operators in . shows all of Ruby's math operators, including operator precedence.if statement that tests whether a variable has a value of zero:value = 0if value.zero? then puts "value is zero. Did you guess that one?" end
zero? method returns true if the value of value is zero, which it is, so the statement following is executed (and any other statements in the code block if/end). By Ruby convention, any method in Ruby that ends with a question mark returns a Boolean, either true or false. This convention is not enforced, however.case and while, and less familiar ones like until and unless. covers all of the conditional statements you'll find in Ruby.pacific = [ "Washington", "Oregon", "California"]
pacific. It holds three strings—the names of the three states that make up the west coast of the United States. These strings are the elements of the array. The elements of an array can be of any Ruby kind, not just strings, of course. This is only one way to define an array. There are a number of other ways you could do this, as you'll see in .[] method.pacific[0] # => "Washington"
0, Washington. You can learn all about Ruby arrays in .pacific = { "WA" => "Washington", "OR" => "Oregon", "CA" => "California" }=>) with a key. One of the ways you can access the values in a hash is by their keys. To access the value Oregon from the hash, you could use Hash's [] method.pacific["OR"] # => "Oregon"
OR returns the value Oregon. The keys and values can be of any kind, not just strings. You can learn more about hashes in .hello, created with the keywords def and end:def hello puts "Hello, Matz!" end hello # => Hello, Matz!
hello method simply outputs a string with puts. On the flip side, you can undefine a method with undef.undef hello # undefines the method named hello
hello # try calling this method now
NameError: undefined local variable or method 'hello' for main:Object
from (irb):11
from :0repeat method:def repeat( word, times )
puts word * times
end
repeat("Hello! ", 3) # => Hello! Hello! Hello!
repeat "Good-bye! ", 4 # => Good-bye! Good-bye! Good-bye! Good-bye!repeat method has two arguments, word and times. You can call a method that has arguments with or without parentheses around the arguments. You can even define method arguments without parentheses, but I don't usually do it that way.+. Each line that follows is actually a valid call to the Fixnum + method:10 + 2 # => 12 10.+ 2 # => 12 (10).+(2) # => 12
return statement. In Ruby, the last value in a method is returned, with or without an explicit return statement. This is a Ruby idiom. Here's how to do it in irb:matz that just contains a string:rb(main):001:0> def matz irb(main):002:1> "Hello, Matz!" irb(main):003:1> end => nil
matz method, and you will see its output. This is available in irbpacific? Here it is again:pacific = [ "Washington", "Oregon", "California" ]
pacific to retrieve all of its elements, one at a time, with the each method. Here is one way to do it:pacific.each do |element|
puts element
end|element|) can be any name you want. The block uses it as a local variable to keep track of every element in the array, and later uses it to do something with the element. This block uses puts to print each element in the array:Washington Oregon California
do/end with a pair of braces, as is commonly done, to make things a bit tighter (by the way, braces actually have a higher precedence than do/end):pacific.each { |e| puts e }each methods in them, such as Array, Hash, and String. But don't get the wrong idea. Iterating over data structures isn't the only way to use blocks. Let me give you a simple example using yield, a Ruby keyword.gimme that contains nothing more than a yield statement:def gimmeyield
endyield does, call gimme alone and see what happens:gimme
LocalJumpError:no block given
from (irb):11:in `gimme'
from (irb):13
from :0yield is to execute the code block that is associated with the method. That was missing in the call to gimme. We can avoid this error by using the block_given? method from Kernel. Redefine gimme with an if statement:def gimme
ifblock_given?
yield
else
puts "I'm blockless!"
end
end:).to_sym or intern methods on a string or by assigning a symbol to a symbol. To understand this better, let's take a string on a roundtrip from a string to a symbol and back to a string.name = "Matz" name.to_sym # => :Matz :Matz.id2name # => "Matz" name == :Matz.id2name # => true
name is magically transformed into the label of a symbol. So what?Symbol.all_symbols
try blocks; in Ruby, you would just use a begin block. catch statements in Java and C++ are used where Ruby has rescue statements. Where Java uses a finally clause, Ruby uses ensure.===) on the left margin set off a heading, and indented text is formatted as code. RDoc can generate output as HTML, XML, ri (Ruby information), or Windows help (chm) files.ri Kernel.print
----------------------------------------------------------- Kernel#print
print(obj, ...) => nil
------------------------------------------------------------------------
Prints each object in turn to +$stdout+. If the output field
separator (+$,+) is not +nil+, its contents will appear between
each field. If the output record separator (+$\+) is not +nil+, it
will be appended to the output. If no arguments are given, prints
+$_+. Objects that aren't strings will be converted by calling
their +to_s+ method.
print "cat", [1,2,3], 99, "\n"
$, = ", "
$\ = "\n"
print "cat", [1,2,3], 99
_produces:_
cat12399
cat, 1, 2, 3, 99Object class include??, what does that signify by convention?if and while, are standard fare and quite familiar to programmers, while others, like unless and until, are not. Think of control structures, which contain conditional statements, as lie detector tests. In every instance, when you use a control structure with a conditional, you are asking if something is true or false. When you get the desired answer—true or false depending on how you've designed your code—the code block associated with the control is executed.rescue and ensure, which are used for exception handling, are not explained here. They are discussed in .if statement—one of the most common structures in just about any programming language.if 1 == 1 then print "True!" end
==) 1, which it does, then the if statement returns true, and the code block, consisting only of a print statement, will execute. (This if statement, by the way, could be typed out on one line.)x = 256 if x == 256 puts "x equals 256" end # => x equals 256
then from the if statement. You don't have to use it in this instance. In addition, you don't have to use end if you write this code all on one line, like so:x = 256 if x == 256 then puts "x equals 256" end
if after puts, and you can drop then and end.x = 256 puts "x equals 256" if x == 256
if is referred to as a statement modifier. You can do this with other control structures, as you will see later on.if statement is by replacing the then with a colon (:), like this:x = 256
if x == 256: puts "x equals 256" endx so that it won't return true when fed to if