Features of the Ruby Language
Hello World
www.flickr.com/photos/rappensuncle/85831251/
Hello World
- Function declaration.
- String literal.
- Prints a line.
def hello_world
puts 'Hello World'
end
hello_world
Hello World
Hello World
- Comments start with #.
- The "return" keyword is optional.
- Semicolons are optional.
def hello_world
# Returns a String
'Hello World' # Inline comment
end
puts hello_world
Hello World
Strings
www.flickr.com/photos/chris_radcliff/93701651/
Strings
- String literals can be single quoted or double quoted.
- Single quoted Strings are more efficient.
- Double quoted Strings support expression interpolation.
a = 'Hello World'
b = "The string #{a} \n is #{a.length()} characters long."
puts a
print b
Hello World
The string Hello World
is 11 characters long.
Numbers
www.flickr.com/photos/wrhowell/41684973/
Numbers
- Integers can be any length up to a max determined by free memory.
- Floats are declared with a decimal and/or exponent (2.8e10)
- Hex (0x2A) and Octal numbers (0322) are supported.
n = 1
n = 2.5 + n
puts n
3.5
Numbers
- Integer classes are Fixnum and Bignum.
- Methods can be called on any object.
n = 1
m = 10000 * 200000
puts n.class
puts m.class
puts -12.abs
Fixnum
Bignum
12
Objects
www.flickr.com/photos/kubina/50366633/
Objects
- In Ruby -12 is a Fixnum object.
- Java requires another class.
- Message sent to Fixnum to call abs method.
puts -12.abs
System.out.println(Math.abs(-12));
Objects
- Object is the parent class of all objects
- Object's methods are available to all classes.
Object
==, ===, =~, __id__, __send__, class, clone, dclone, display, dup,
eql?, equal?, extend, freeze, frozen?, hash, id, initialize_copy,
inspect, instance_eval, instance_of?, instance_variable_get,
instance_variable_set, instance_variables, is_a?, kind_of?, method,
methods, nil?, object_id, private_methods, protected_methods,
public_methods, remove_instance_variable, respond_to?, send,
singleton_method_added, singleton_method_removed,
singleton_method_undefined, singleton_methods, taint, tainted?,
to_a, to_s, type, untaint
The word "object" is commonly used to refer to an instance of a class.
Objects
- In Ruby objects are everywhere.
- Including nil.
a = nil
a.inspect => "nil"
a.class => NilClass
a.nil? => true
a = 2 => 2
a.nil? => false
Variables
www.flickr.com/photos/kubina/64654463/
Variables
- Variables hold a reference to an object.
- Variables are not objects.
greeting1 = 'Good Morning'
greeting2 = greeting1
greeting1[5..12] = 'Day'
puts greeting1
puts greeting2
Good Day
Good Day
Constants
- Constants start with a capital letter.
- Constants can be changed but generate a warning.
PI = 3.14
PI = 3.14159 => warning: already initialized constant PI
Duck Typing
www.flickr.com/photos/njh/13349747/
Dynamic Typing
- Types of variables and return types of methods are not declared.
- Dynamically and Strongly Typed
num = 1
str = '2'
num + str => Type Error: String can't be coerced into Fixnum
num + str.to_i => 3
Duck Typing
- Duck Typing:
If it walks and talks like a duck then treat it like a duck.
- Objects are used based on their behaviour instead of the type of duck they are.
def display_length(object)
puts object.length()
end
display_length('Hello') => 5
display_length(['H', 'e', 'l', 'l', 'o']) => 5
display_length(23) => NoMethodError: undefined method
`length' for 23:Fixnum
Methods
- def <method name>(<parm1>, <parm2>)
- Parentheses are optional but recommended.
- Delimited with the "end" keyword.
def double(num)
num * 2
end
puts(double(4))
puts double 5
8
10
Control Structures
www.flickr.com/photos/kubina/114126906/
Control Structures
- The "end" keyword is used to signify end of a body.
if (foo)
puts 'foo'
elsif (bar)
puts 'bar'
else
puts 'rar'
end
name = case
when num == 1: "one"
when num == 2: "two"
when num == 3: "three"
else
num.to_s
end
Control Structures
- Use statement modifiers for single line evalution.
if num > 0
puts 'positive'
end
puts 'positive' if num > 0
num = num + num while num < 100
Class
www.flickr.com/photos/kubina/110123784/
Class
- Default constructor for a class is "new".
- new allocates memory and calls initialize.
class Ball
def initialize(color, radius, material)
@color = color
@radius = radius
@material = material
end
end
ball = Ball.new("red", 5, "plastic")
Class
- Instance variables start with '@'.
- Override inherited method to_s.
class Ball
def to_s
"#{@color.capitalize} ball made of #{@material}."
end
end
puts ball.to_s
Red ball made of plastic.
Class
- Attributes are shortcut methods that make instance variables accessible.
class Ball
attr_reader :color, :radius, :material
def color=(color)
@color = color
end
end
ball.color => "red"
ball.color=("blue") => "blue"
Class
- Ruby has single class inheritance.
- Use super to access parent class.
class BasketBall < Ball
def initialize(color, radius, material, brand)
super(color, radius, material)
@brand = brand
end
end
Mixins
- Mixins provide most features of multiple inheritance.
- Use "include" to mixin a module.
module Formulas
PI = 3.14159
def surface_area(radius)
(radius**2) * PI
end
end
On to Collections and Blocks
www.flickr.com/photos/nabeel/50480403/