Introducing Ruby

Download Report

Transcript Introducing Ruby

Web Science Stream
Introducing Ruby
Dr Alexiei Dingli
1
What is Ruby?
• Originated in Japan in 1995
and it was created by Yakihiro
Matsumoto
• High level programming
language
• Scripting language which is
interpreted
• Object Oriented
2
What about performance?
• 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?
3
What about OOP?
• 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
4
Interactive Ruby Shell
• 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
5
As easy as 1, 2, 3
• 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?
6
In Ruby everything is an object!
• 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?
7
More and more classes
1.class
Fixnum
What if we try
Fixnum.class
8
The world is full of numbers ...
•
•
•
•
•
•
•
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
9
Numbering exercises
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
10
Literal objects
• 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
11
Even more strings ...
•
•
•
•
•
•
•
•
•
•
•
“Hello “ + “World”
“hi “ * 3
“1” + “2”
“1” * 2
“Hello”.capitalize
“Hello”.reverse
“Hello”.upcase
“Hello”.downcase
“Hello”.swapcase
“a”.next
“aa”.next
12
String exercise
•
•
•
•
•
"hello".length + "world".length
"".empty?
"Zoo".include? "oo"
"cats".chop
How do you display your name
backwards?
13
Easy conversions ...
• Convert anything to ...
– .to_s
– .to_i
– .to_f
String
Integer
Float
• What’s the result of ...
– 2.to_s
14
Variables
• Name of an object
– city = “Valletta”
• Variables always start with a lowercase
letter
15
Constants
• 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”
16
Shortcuts
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
17
Our first program
Create a first.rb file and type the following ...
name = “Tom”
puts “Hello “ + name + “. How are you?”
no1 = 2
no2 = 4
no3 = no1 + no2
18
puts “The answer is “ + no3.to_s
Some tips and conventions
• 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
19
Loops
4.times do
puts “Hello”
end
Exercise
What is the sum of all the integers from 1 to 1000?
20
Getting user input
name = gets
To remove any carriage returns or new lines
use chomp
“Alexiei\n”.chomp
21
Input exercise
• Write a small program which asks for your
age, calculates the year you were born
and displays:
You were born in 19XX
22
Conditions
if city == “Valletta"
licence = “V Licence”
else
licence = “normal”
end
= is an assignment
== is a boolean comparison
23
Conditions
if city == “Valletta"
licence = “V Licence”
elsif city == “Mdina”
licence = “M Licence”
else
licence = “normal”
end
24
Note that only the first elsif that returns true gets
executed
Comparisons
•
•
•
•
•
•
==
!=
>
<
>=
<=
equal
not equal to
greater than
less than
greater than or equal to
less than or equal to
25
String comparison
“9” < “D”
“a” < “b”
“h” == “h”
“H” == “h”
“Z” <= “b”
“j” != “r”
26
While loop
count = 0
while count < 10
count += 1
end
27
More tips and conventions
• Use proper indentation
• Write comments when needed
#
I’m a comment and can write whatever i want
28
Arrays
>> numbers = [ "zero", "one", "two", "three", "four" ]
=> ["zero", "one", "two", "three", "four"]
>> numbers.class
=> Array
>> numbers[0]
=> "zero"
29
Fun with Arrays
names = [ "Melissa", "Daniel", "Samantha", "Jeffrey"]
What about ...
names.sort
names.reverse
names.length
names + [“Tom”]
names - [“Daniel”]
names * 2
puts names.to_s
30
Let’s iterate
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?
31
What’s in a Hash?
addressBook = {
“Valletta" => “Tom",
“Sliema" => “Jack",
“Mdina" => “Ben”
}
32
Iterating Hashes
addressBook.each do |key, value|
puts key + " => " + value
end
There is also ...
addressBook.each_key do |key|
addressBook.each_value do |value|
33
Functions ...
• Not associated with any other object
def say_hi
puts "Hello, How are you?"
end
say_hi
34
Function parameters ...
def say_hi(name)
puts "Hello " + name + ", How are you?"
end
say_hi("Daniel")
say_hi "Sandy"
35
Classes
• 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.
36
Example class
class Address
def initialize(street)
@street = street
end
end
address = Address.new(“2 Republic Str")
37
Example class with return
class Address
def initialize(street)
@street = street
end
def street
@street
end
end
>> address.street
=> " 2 Republic Str"
38
Shortcut to class with return
class Address def
attr_reader: street
initialize(street)
@street = street
end
end
39
Shortcut to set a variable
class Address def
attr_reader: street
attr_writer: street
initialize(street)
@street = street
end
end
40
Shortcut to getting and setting a
variable in one go
class Address def
attr_accessor: street
initialize(street)
@street = street
end
end
41
Private vrs Public classes
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
42
Using classes
• Save them in a className.rb file
• Make use of the following command
require “className“
• Just use the classes normally
43
Some final guidelines
• 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. 44
Questions?
45