450 likes | 558 Views
Web Science Stream. Introducing Ruby. 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. What about performance?. Code caching
E N D
Web Science Stream Introducing Ruby
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
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?
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
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
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?
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?
More and more classes 1.class • Fixnum What if we try Fixnum.class
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
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
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
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
String exercise • "hello".length + "world".length • "".empty? • "Zoo".include? "oo" • "cats".chop • How do you display your name backwards?
Easy conversions ... • Convert anything to ... • .to_s String • .to_i Integer • .to_f Float • What’s the result of ... • 2.to_s
Variables • Name of an object • city = “Valletta” • Variables always start with a lowercase letter
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”
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 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
Loops 4.times do puts “Hello” end Exercise What is the sum of all the integers from 1 to 1000?
Getting user input name = gets To remove any carriage returns or new lines use chomp “Alexiei\n”.chomp
Input exercise • Write a small program which asks for your age, calculates the year you were born and displays: You were born in 19XX
Conditions if city == “Valletta" licence = “V Licence” else licence = “normal” end = is an assignment == is a boolean comparison
Conditions if city == “Valletta" licence = “V Licence” elsifcity == “Mdina” licence = “M Licence” else licence = “normal” end 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
String comparison “9” < “D” “a” < “b” “h” == “h” “H” == “h” “Z” <= “b” “j” != “r”
While loop count = 0 while count < 10 count += 1 end
More tips and conventions • Use proper indentation • Write comments when needed # I’m a comment and can write whatever i want
Arrays >> numbers = [ "zero", "one", "two", "three", "four" ] => ["zero", "one", "two", "three", "four"] >> numbers.class => Array >> numbers[0] => "zero"
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
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?
What’s in a Hash? addressBook = { “Valletta" => “Tom", “Sliema" => “Jack", “Mdina" => “Ben” }
Iterating Hashes addressBook.each do |key, value| puts key + " => " + value end There is also ... addressBook.each_key do |key| addressBook.each_value do |value|
Functions ... • Not associated with any other object def say_hi puts "Hello, How are you?" end say_hi
Function parameters ... def say_hi(name) puts "Hello " + name + ", How are you?" end say_hi("Daniel") say_hi "Sandy"
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.
Example class class Address def initialize(street) @street = street end end address = Address.new(“2 Republic Str")
Example class with return class Address definitialize(street) @street = street end def street @street end end >> address.street => " 2 Republic Str"
Shortcut to class with return class Address def attr_reader: street initialize(street) @street = street end end
Shortcut to set a variable class Address def attr_reader: street attr_writer: street initialize(street) @street = street end end
Shortcut to getting and setting a variable in one go class Address def attr_accessor: street initialize(street) @street = street end end
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
Using classes • Save them in a className.rb file • Make use of the following command require “className“ • Just use the classes normally
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.