Download - Web Science Stream
1
Dr Alexiei Dingli
Web Science Stream
Introducing Ruby
2
• Originated in Japan in 1995 and it was created by Yakihiro Matsumoto
• High level programming language
• Scripting language which is interpreted
• Object Oriented
What is Ruby?
3
• Code caching– Caching the output of a script for reuse rather
than executing the script every time
• Persistent interpreters– Loading the interpreter once and keeping it
running
• What about your performance when developing an application?
What about performance?
4
• Program made of objects capable of communicating with other objects
• Each object can store data internally
• Objects with similar characteristics are instances of the same class
What about OOP?
5
• The shell where we can input ruby commands
Note: In windows we won’t be using a standard DOS box but use the “Open Ruby Console Window” from the Instant Rails application
Interactive Ruby Shell
6
• Open a Ruby Console Window• Type “irb”• And we’re ready to start ...
– Type “1”– Type “2”– Type “3”– What is the result?– Is it the same?
As easy as 1, 2, 3
7
• The result might look the same as the input but– Its not the same number– The output is a Ruby object
• As a proof, type– 1.class– What’s the result?
In Ruby everything is an object!
8
1.classÞ Fixnum
What if we try
Fixnum.class
More and more classes
9
• 1 + 2 • 4 – 3 • 3 / 2 (Integers)• 3.0 / 2.0 (Floats)• 3 ** 2 (3 to the power of 2)• 5 % 2 (5 remainder 2)• 17_000_000_000_000_000_000
(What’s the effect of the underscore?)
• 1.7e19
The world is full of numbers ...
10
1. What’s the result of
17_000_000_000_000_000_000 == 1.7e19
2. What happens when you write
googol = 10.0 ** 100
googolplex = 10.0 ** googol
Numbering exercises
11
• Strings or numbers that appear directly in the code– String literal
Irb> “The dog ate a bone”
=> “The dog ate a bone”
Irb> “The dog ate a bone”.class
=> String
Irb> “The dog ate a bone”.length
=> 18
Literal objects
12
• “Hello “ + “World”• “hi “ * 3• “1” + “2”• “1” * 2• “Hello”.capitalize• “Hello”.reverse• “Hello”.upcase• “Hello”.downcase• “Hello”.swapcase• “a”.next• “aa”.next
Even more strings ...
13
• "hello".length + "world".length • "".empty? • "Zoo".include? "oo" • "cats".chop• How do you display your name
backwards?
String exercise
14
• Convert anything to ...– .to_s String– .to_i Integer– .to_f Float
• What’s the result of ...– 2.to_s
Easy conversions ...
15
• Name of an object– city = “Valletta”
• Variables always start with a lowercase letter
Variables
16
• Name of an object– City = “Valletta”
• Constants always start with an uppercase letter• Constants should not change, if you try Ruby will send
a warning• Try
– City = “Valletta”– City = “Mdina”
Constants
17
var = var + 2 var += 2 Add 2 to var
var = var - 3 var -= 3 Subtract 3 from var
var = var * 6 var *= 6 Multiply var by 6
var = var / 2 var /= 2 Divide var by 2
var = var** 3 var **=3 Cube var
var = var % 4 var %= 4 var modulo 4
Shortcuts
18
Create a first.rb file and type the following ...
name = “Tom”
puts “Hello “ + name + “. How are you?”
no1 = 2
no2 = 4
no3 = no1 + no2
puts “The answer is “ + no3.to_s
Our first program
19
• Please use meaningful names for variables ...– age vrs a
• Use the following approach with Multiwords– studentAge or student_age vrs studentage
• Don’t be afraid to use constants where values don’t change
• Use irb when you need to test small sections of code
• When you need help use ri XXXX– Eg ri String – Eg ri String#upcase
Some tips and conventions
20
4.times do
puts “Hello”
end
ExerciseWhat is the sum of all the integers from 1 to 1000?
Loops
21
name = gets
To remove any carriage returns or new lines use chomp
“Alexiei\n”.chomp
Getting user input
22
• Write a small program which asks for your age, calculates the year you were born and displays:
You were born in 19XX
Input exercise
23
if city == “Valletta"
licence = “V Licence”
else
licence = “normal”
end
= is an assignment
== is a boolean comparison
Conditions
24
if city == “Valletta"
licence = “V Licence”
elsif city == “Mdina”
licence = “M Licence”
else
licence = “normal”
end
Note that only the first elsif that returns true gets executed
Conditions
25
• == equal• != not equal to• > greater than• < less than• >= greater than or equal to• <= less than or equal to
Comparisons
26
“9” < “D”
“a” < “b”
“h” == “h”
“H” == “h”
“Z” <= “b”
“j” != “r”
String comparison
27
count = 0
while count < 10
count += 1
end
While loop
28
• Use proper indentation
• Write comments when needed
# I’m a comment and can write whatever i want
More tips and conventions
29
>> numbers = [ "zero", "one", "two", "three", "four" ]
=> ["zero", "one", "two", "three", "four"]
>> numbers.class
=> Array
>> numbers[0]
=> "zero"
Arrays
30
names = [ "Melissa", "Daniel", "Samantha", "Jeffrey"]
What about ...
names.sort
names.reverse
names.length
names + [“Tom”]
names - [“Daniel”]
names * 2
puts names.to_s
Fun with Arrays
31
names.each do |friend|
puts “I have a friend called “ + friend
end
What about using 4.times or ...
names.length.times do |i|
puts "I have a friend called " + names[i]
end
What if I want to print my friends in sorted order?
Let’s iterate
32
addressBook = {
“Valletta" => “Tom",
“Sliema" => “Jack",
“Mdina" => “Ben”
}
What’s in a Hash?
33
addressBook.each do |key, value|
puts key + " => " + value
end
There is also ...
addressBook.each_key do |key|
addressBook.each_value do |value|
Iterating Hashes
34
• Not associated with any other object
def say_hi
puts "Hello, How are you?"
end
say_hi
Functions ...
35
def say_hi(name)
puts "Hello " + name + ", How are you?"
end
say_hi("Daniel")
say_hi "Sandy"
Function parameters ...
36
• The class keyword defines a class
• By defining a method inside this class, we are associating it with this class
• The initialize method is what actually constructs the data structure. Every class must contain an initialize method.
• The @ sign in front of variables distinguishes the variable as an object variable.
Classes
37
class Address
def initialize(street)
@street = street
end
end
address = Address.new(“2 Republic Str")
Example class
38
class Address
def initialize(street)
@street = street
end
def street
@street
end
end
>> address.street
=> " 2 Republic Str"
Example class with return
39
class Address def
attr_reader: street
initialize(street)
@street = street
end
end
Shortcut to class with return
40
class Address def
attr_reader: street
attr_writer: street
initialize(street)
@street = street
end
end
Shortcut to set a variable
41
class Address def
attr_accessor: street
initialize(street)
@street = street
end
end
Shortcut to getting and setting a variable in one go
42
class SomeClass
def method1 # default to public
...
end
private # subsequent methods are private.
def method2 # private method
...
end
def method3 # private method
...
end
public # Set back to public.
def method4 # public method
...
end
end
Private vrs Public classes
43
• Save them in a className.rb file
• Make use of the following command
require “className“
• Just use the classes normally
Using classes
44
• If you can't sumarize in one sentence what the function does, it's probably too complicated
• If you have to scroll to see the entire function, it is too long
• Studies suggest that a person can only keep track of at most 7 or so things at one time. If your function has more than 5 or 6 variables, it is probably too long.
Some final guidelines
45
Questions?