Documente Academic
Documente Profesional
Documente Cultură
Introduction
This is a small Ruby tutorial that should take no more than 20 minutes to complete. It
makes the assumption that you already have Ruby installed. (If you do not have Ruby
on your computer install it before you get started.)
Interactive Ruby
Ruby comes with a program that will show the results of any Ruby statements you feed
it. Playing with Ruby code in interactive sessions like this is a terrific way to learn the
language.
If you’re using Mac OS X open up Terminal and type irb , then hit enter.
If you’re using Linux, open up a shell and type irb and hit enter.
If you’re using Windows, open Interactive Ruby from the Ruby section of your Start
Menu.
irb(main):001:0>
irb(main):003:0> 3+2
=> 5
Three plus two. Easy enough. What about three times two? You could type it in, it’s
short enough, but you may also be able to go up and change what you just entered. Try
hitting the up-arrow on your keyboard and see if it brings up the line with 3+2 on it. If it
does, you can use the left arrow key to move just after the + sign and then use
backspace to change it to a * sign.
irb(main):004:0> 3*2
=> 6
irb(main):005:0> 3**2
=> 9
In Ruby ** is the way you say “to the power of”. But what if you want to go the other
way and find the square root of something?
irb(main):006:0> Math.sqrt(9)
=> 3.0
Ok, wait, what was that last one? If you guessed, “it was figuring out the square root of
nine,” you’re right. But let’s take a closer look at things. First of all, what’s Math ?
What if we want to remember the result of some of this math? Assign the result to a
variable.
irb(main):007:0> a = 3 ** 2
=> 9
irb(main):008:0> b = 4 ** 2
=> 16
irb(main):009:0> Math.sqrt(a+b)
=> 5.0
As great as this is for a calculator, we’re getting away from the traditional Hello
World message that beginning tutorials are supposed to focus on…so let’s go back to
that.
What if we want to say “Hello” a lot without getting our fingers all tired? We need to
define a method!
irb(main):010:0> def hi
irb(main):011:1> puts "Hello World!"
irb(main):012:1> end
=> :hi
The code def hi starts the definition of the method. It tells Ruby that we’re defining a
method, that its name is hi . The next line is the body of the method, the same line we
saw earlier: puts "Hello World" . Finally, the last line end tells Ruby we’re done defining
the method. Ruby’s response => :hi tells us that it knows we’re done defining the
method. This response could be => nil for Ruby 2.0 and earlier versions. But, it’s not
important here, so let’s go on.
irb(main):013:0> hi
Hello World!
=> nil
irb(main):014:0> hi()
Hello World!
=> nil
Well, that was easy. Calling a method in Ruby is as easy as just mentioning its name to
Ruby. If the method doesn’t take parameters that’s all you need. You can add empty
parentheses if you’d like, but they’re not needed.
What if we want to say hello to one person, and not the whole world? Just redefine hi to
take a name as a parameter.
irb(main):015:0> def hi(name)
irb(main):016:1> puts "Hello #{name}!"
irb(main):017:1> end
=> :hi
irb(main):018:0> hi("Matz")
Hello Matz!
=> nil
So it works… but let’s take a second to see what’s going on here.
irb(main):039:0> Greeter.instance_methods
=> [:say_hi, :say_bye, :instance_of?, :public_send,
:instance_variable_get, :instance_variable_set,
:instance_variable_defined?, :remove_instance_variable,
:private_methods, :kind_of?, :instance_variables, :tap,
:is_a?, :extend, :define_singleton_method, :to_enum,
:enum_for, :<=>, :===, :=~, :!~, :eql?, :respond_to?,
:freeze, :inspect, :display, :send, :object_id, :to_s,
:method, :public_method, :singleton_method, :nil?, :hash,
:class, :singleton_class, :clone, :dup, :itself, :taint,
:tainted?, :untaint, :untrust, :trust, :untrusted?, :methods,
:protected_methods, :frozen?, :public_methods, :singleton_methods,
:!, :==, :!=, :__send__, :equal?, :instance_eval, :instance_exec, :__id__]
Whoa. That’s a lot of methods. We only defined two methods. What’s going on here?
Well this is all of the methods for Greeter objects, a complete list, including ones
defined by ancestor classes. If we want to just list methods defined for Greeter we can
tell it to not include ancestors by passing it the parameter false , meaning we don’t want
methods defined by ancestors.
irb(main):040:0> Greeter.instance_methods(false)
=> [:say_hi, :say_bye]
Ah, that’s more like it. So let’s see which methods our greeter object responds to:
irb(main):041:0> greeter.respond_to?("name")
=> false
irb(main):042:0> greeter.respond_to?("say_hi")
=> true
irb(main):043:0> greeter.respond_to?("to_s")
=> true
So, it knows say_hi , and to_s (meaning convert something to a string, a method that’s
defined by default for every object), but it doesn’t know name .
#!/usr/bin/env ruby
class MegaGreeter
attr_accessor :names
# Say hi to everybody
def say_hi
if @names.nil?
puts "..."
elsif @names.respond_to?("each")
# @names is a list of some kind, iterate!
@names.each do |name|
puts "Hello #{name}!"
end
else
puts "Hello #{@names}!"
end
end
if __FILE__ == $0
mg = MegaGreeter.new
mg.say_hi
mg.say_bye
# Change to nil
mg.names = nil
mg.say_hi
mg.say_bye
end
Save this file as “ri20min.rb”, and run it as “ruby ri20min.rb”. The output should be:
Hello World!
Goodbye World. Come back soon!
Hello Zeke!
Goodbye Zeke. Come back soon!
Hello Albert!
Hello Brenda!
Hello Charles!
Hello Dave!
Hello Engelbert!
Goodbye Albert, Brenda, Charles, Dave, Engelbert. Come
back soon!
...
...
There are a lot of new things thrown into this final example that we can take a deeper
look at.
So, looking deeper at our new program, notice the initial lines, which begin with a hash
mark (#). In Ruby, anything on a line after a hash mark is a comment and is ignored by
the interpreter. The first line of the file is a special case, and under a Unix-like operating
system tells the shell how to run the file. The rest of the comments are there just for
clarity.
@names.each do |name|
puts "Hello #{name}!"
end
each is a method that accepts a block of code then runs that block of code for every
element in a list, and the bit between do and end is just such a block. A block is like an
anonymous function or lambda . The variable between pipe characters is the parameter
for this block.
What happens here is that for every entry in a list, name is bound to that list element,
and then the expression puts "Hello #{name}!" is run with that name.
Most other programming languages handle going over a list using the for loop, which in
C looks something like:
for (i=0; i<number_of_elements; i++)
{
do_something_with(element[i]);
}
This works, but isn’t very elegant. You need a throw-away variable like i , have to figure
out how long the list is, and have to explain how to walk over the list. The Ruby way is
much more elegant, all the housekeeping details are hidden within the each method, all
you need to do is to tell it what to do with each element. Internally, the each method will
essentially call yield "Albert" , then yield "Brenda" and then yield "Charles" , and so
on.
if __FILE__ == $0
__FILE__ is the magic variable that contains the name of the current file. $0 is the name
of the file used to start the program. This check says “If this is the main file being
used…” This allows a file to be used as a library, and not to execute code in that
context, but if the file is being used as an executable, then execute that code.
If so, please head on over to our Documentation area, which rounds up links to manuals
and tutorials, all freely available online.
Or, if you’d really like to dig into a book, check the book list (off-site link) for titles
available for sale online or at your local bookseller.
Ruby is installed on most Linux distributions by default. Follow these steps to determine
if Ruby is installed and, if not, install the Ruby interpreter on your Linux computer.
Difficulty: Easy
Time Required: 15 minutes
Here's How:
1. Open a terminal window. It may also be referred to as a "shell" or "bash shell" in the
menus. On Ubuntu, go toApplications -> Accessories -> Terminal.
2. Run the command which ruby.
1. If you see a path such as /usr/bin/ruby, Ruby is installed. If you don't see any response
or get an error message, Ruby is not installed.
2. To verify that you have a current version of Ruby, run the command ruby -v.
3. Compare the version number returned with the version number on the Ruby download
page. These numbers don't have to be exact, but if you are running a version that's too
old, some of the features may not work correctly.
1. Install appropriate Ruby packages. This differs between distributions, but on Ubuntu run
the following command:
sudo apt-get install ruby1.8 ruby1.8-dev irb rdoc ri
2. Open a text editor and save the following as test.rb.
#!/usr/bin/env ruby