The Ruby Programming Language
The Ruby Programming Language
Object Orientation
Ruby is fully object oriented; everything is an object. Inheritance is shown by < instead of extends.
Java: class Student extends Person Ruby: class Student < Person class Person < ActiveRecord:: Base Modules are like namespaces in html and xml.
Access controls are similar to Java: public, protected and private. Each controls everything following it in a class. All variables are accessed by reference.
Ruby is weakly typed. Variables receive their types during assignment. There is no boolean type, but everything has a value. False and nil are false and all other objects are true. Instance variables (class variables) begin with the @ sign.
Global variables begin with two @ signs. They are almost never used. Symbols seem to be peculiar to Ruby. They begin with a colon.
Blocks
If a block consists of a single line, it is enclosed in curly braces. Usually blocks begin with a control statement and are terminated with the keyword, end. Indentation, usually two spaces, is used to indicate what is in the block. Common errors are to have either too few or too many ends. Variables within a block are local to the block unless they are instance variables starting with the @ sign. Methods begin with the keyword, def, and are terminated with an end. Parameters are enclosed with parentheses. If a method has no parameters, the parentheses are optional.
Ruby has girl = Person.new(Alice, 5). Java has Person girl = new Person(Alice,5); Java comments begin with //; Rubys with #. In Ruby we can write
Data Structures
Arrays
Indexed with integers starting at 0. Contents do not have to all be the same type. Contents can be assigned in a list using square brackets.
order = [blue, 6, 24.95] Arrays are objects so must be instantiated with new.
Hash Tables
Key value pairs Keys are almost always symbols Contents can be assigned in a list of key-value pairs using curly braces.
order = {:color => blue, :size => 6, :price => 24.95} @size = order[:size]
Iterator each
sum = 0 [1..10].each do |count| sum += count end puts sum count is a parameter to the block and has no value outside of it.
Exceptions
begin rescue rescue ensure end rescue and ensure are the same as catch and finally Ruby also has throw and catch, similar to Java
Conventions
Class names begin with upper case letters. Method and variable names use lower case. For names with more than one word:
class ActiveRecord
Single record is course Table is called courses But the model class is called Course.
References
Dave Thomas, Programming Ruby 1.9, the Pragmatic Progammers Guide, 3rd edition, The Pragmatic Programmers, 2009 Sam Ruby, Dave Thomas and David Heinemeier Hannson, Agile Web Development with Rails, 4th edition, 2010, Chapter 4