For the next three weeks we will be looking at the Ruby on Rails web application framework. Ruby on Rails uses the Ruby programming language, which we will look at this week.
Ruby is a scripting language, much like PHP or Perl; rather like PHP it is not strongly typed, so you don't have to declare variables as int, float, double etc. It is open source and runs on all common operating systems.
Here is 'hello world' in Ruby:
puts "Hello world!"As can be seen, you don't have to declare a main() method or include any header files, so it's very easy to get started!
Here is an example which uses variables:
a=1 b=2 puts a+b a="Hello " b="World" puts a+bHopefully very simple. Notice how you can re-use the same variable and store different data in it: originally a and b contained numbers, then later they contain strings.
If you try this:
a="Today is the " b=2 c="nd of the month" puts a+b+cyou will get an error, as you're trying to add numbers (integers) and strings. What you have to do is convert the number 2 to a string which you can do using to_s, as follows:
a="Today is the " b=2 c="nd of the month" puts a + b.to_s + cIn a similar way, you can use to_i to convert from string to integer, e.g.
a="12345".to_i puts a+1will display 12346.
The syntax for loops in Ruby is a bit different to other languages such as PHP, JavaScript and Java. For example, here is a for loop in Ruby, which counts from 1 to 10:
for i in 1...10
puts i
end
Note how we specify the range to count from and to. Note that
we count up to one less than the second number. So this example will
count from 1 to 9.
There is another way to perform a certain action a given number of times, using the do loop:
3.times do
puts "Hello"
end
The while loop also exists, though is probably used less than the above examples as it is more long winded:
i = 1
while i <= 10
puts i
i=i+1
end
Like every language, Ruby allows you to store several related items inside an array. Here is an example of how you set up an array in Ruby:
sales = [ 1000, 2000, 3000, 5000, 8000, 13000, 21000, 34000, 55000, 89000 ]You then index the array the same as in most other commonly used languages using a numerical index starting from 0, for example:
puts sales[0] puts sales[2] puts sales[9]would display
1000 3000 89000You can use a for loop on an array:
sales = [ 1000, 2000, 3000, 5000, 8000, 13000, 21000, 34000, 55000, 89000 ]
for i in 0...10
puts sales[i]
end
but there is a more efficient way of looping through an array in Ruby, using the
in loop:
for sale in sales
puts sale
end
This example loops through each member of the sales
array in turn, referencing
each as sale; the variable
sale will always represent the current member of the sales array.
Still another way is to use the each loop, as follows:
sales.each do |sale|
puts sale
end
The each is an example of something called an iterator method
which is one of the more powerful features of Ruby. each is actually
a method of the built in Array class, which loops through an
array and performs some action on each member; the section of code between the
do
and the
end
is referred to as a Ruby code block. The code block is done on
each member of the array. Code blocks and iterators are a powerful feature of
Ruby - see the log book question
below which asks you to look up more detail on Ruby blocks and iterators.
Another way of writing the above is to use curly brackets { and } to define
the code block:
sales.each { |sale| puts sale }
A powerful feature of Ruby is the hash. A hash is an array which can be indexed by non numerical values, such as strings. It is basically the same as an associative array in PHP or a Map in Java. Hashes are typically used when we want to look up a value by a unique, non numerical key. Hashes use curly brackets { and } rather than square brackets [ and ]. For example:
marks = { "Craig" => 63, "James" => 72, "Ben" => 81 }
This sets up a hash called marks which uses student names as the
key and the actual marks as the value. To loop through a hash we use the
each loop again, as follows:
marks.each do |k,v|
puts "Name " + k + " Mark " + v.to_s
end
We loop through each member of the hash marks; each time the loop
runs, k represents the key (the name) and v the value (the
mark).
Ruby is an object orientated language: everything in Ruby is an object, even numbers! We have already looked at objects in JavaScript, so you should know the concept already, so we'll just look at the specific syntax used in Ruby.
Here is how we would define a dog in Ruby:
class Dog
def initialize(name,age,weight)
@name=name
@age=age
@weight=weight
end
def walk
@weight=@weight-1
end
def eat
@weight=@weight+1
end
def print
puts "Name " + @name + " weight " + @weight.to_s + " age " + @age.to_s
end
end
Note the following:
The code above does not actually create any dogs. It is merely a blueprint: a description of how dogs work. This is what a class is. A class is a template for how objects work (e.g. Dog or Person) while an object is an individual example (or instance) of that class. For example Dog is a class, Fido and Lassie are objects. Person is a class, Noel Gallagher and Madonna are objects.
Here is how we would actually create individual Dog objects.
dog1 = Dog.new ("Lassie", 10, 10)
dog2 = Dog.new ("Fido", 5, 20)
We can then do things with the Dog objects, such as feed them or walk them:
dog1.walk dog1.print dog2.walk dog2.printPutting it all together, this Ruby program will define a Dog class and create two Dog objects. The first dog will walk, while the second dog will eat.
class Dog
def initialize(name,age,weight)
@name=name
@age=age
@weight=weight
end
def walk
@weight=@weight-1
end
def eat
@weight=@weight+1
end
def print
puts "Name " + @name + " weight " + @weight.to_s + " age " + @age.to_s
end
end
dog1 = Dog.new ("Lassie", 10, 10)
dog2 = Dog.new ("Fido", 5, 20)
dog1.walk
dog1.print
dog2.eat
dog2.print
Unlike many languages, primitive types, such as numbers, are also objects! Numbers belong to the built-in Fixnum class. Similarly, strings belong to the built-in String class.
For example we can say:
a = 2.to_sand a will contain the string "2". Or:
b = 5.modulo(3)and b will contain 2, which is the remainder you get when you divide 5 by 3. Another example would be:
c = 201.to_s(16)If a parameter is supplied to the to_s method, the result will be a string containing the number represented in that base. So this will give the result c9 which is 201 in base 16 (hexadecimal).
Remember this code example:
names.each do |name|
puts name
end
These are an example of two interesting Ruby features: code
blocks and iterator methods. The idea is that you can write
a code block (the code between the do and the end)
and call the code block from within the method preceding the code block.
Here, each is a method of the Array class.
The each method loops through each member of the array and calls back to
the code block using the yield keyword. Imagine if we wrote our
own:
def do_something_with (an_array)
for member in an_array
yield member
end
end
We could then associate our do_something_with method with a code block
as follows:
a = [ "Fred", "Tom", "John" ]
do_something_with(a) do |n|
puts b
end
What happens here is:
Research Ruby on Rails, including what it is, how it works, what it can do and the general techniques you would use when developing in Rails.