Ruby:Tutorial

From GPWiki
Jump to: navigation, search
40px-broken-icon.png   This page has broken markup.
If you fix this problem, please remove this banner.


Contents

Getting Ruby

For Windows or Mac, you will want to head over to the official Download page, grab the appropriate installer, and go for it. On OSX, install it via DarwinPorts.

Linux

(Yeah, it gets its own section, it sucks, blah blah blah.)

Easy version: Install it from the packages supplied by the distributor.

Full version:

How to Run Ruby

There are several methods to run ruby code. The most straightforward is, of course, to write a script file, and then just run

ruby myscript.rb some optional arguments

On *nix, you can also make the script file executable, and use the hash-bang notation, so a script might look like this: #!/usr/bin/ruby

puts 'This could be your code!'

For quick experimentation, there is also an interactive shell-type interface, called irb (you may need to install it separately). An example session would look like this:

$ irb
irb(main):001:0> puts 'Hello, world!'
Hello, world!
=> nil
irb(main):002:0>

Basic Concepts

Hello World

puts "Hello World"

There is not much more to be said about it, so let us try a more involved example, showing some actual features of the language.

#!/usr/bin/ruby

  1. You guess what it does.

def bottles(n)

 if n>0 then
   "#{n} bottle#{n>1 ? 's' : } of beer"
 else
   "no more bottles of beer"
 end

end

number_of_bottles = 99 number_of_bottles = ARGV[0].to_i if ARGV.size > 0

number_of_bottles.downto(1) do |n|

 puts "#{bottles(n)} on the wall, #{bottles(n)};"
 puts "  take one down, pass it around, #{bottles(n-1)} on the wall."

end

This small snippet demonstrates several features:

Classes

The following example demonstrates a Person class:

class Person

   attr_accessor :name, :age, :height, :weight
   def initialize(name, age, height, weight)
       @name = name
       @age = age
       @height = height
       @weight = weight
   end
   def information
       print "Name: #{name}\nAge: #{age}\nHeight: #{height}\nWeight: #{weight}\n"
   end

end

One could use the class like so:

smith = Person.new("Mr Smith", 20, 5.11, 13.5) smith.information

Would output:

Name: Mr Smith
Age: 20
Height: 5.11
Weight: 13.5

Setters/Getters (or: Love the Assignment)

Consider again the above example of a class. Now, what if we wanted to have a way to store the weight in kg, but provide setters/getters in US pounds? Just add the following methods to the class: def weight_in_lbs

 @weight / 0.4536

end

def weight_in_lbs=(w)

 @weight = w * 0.4536

end

Now you have created transparent access to Person#weight, doing unit conversion on the fly by accessing and assigning Person#weight_in_lbs as you would any "normal" attribute. (Alternatively, you could of course extend the numeric classes to provide #kg_to_lbs and other necessary methods doing the conversion for you...)

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox