ruby. what is ruby? programming language object-oriented interpreted popular- ruby on rails a...
TRANSCRIPT
Ruby
What is Ruby?Programming LanguageObject-orientedInterpreted
Popular- Ruby on Rails a framework for Web Server Programming
Interpreted LanguagesNot compiled like JavaCode is written and then directly executed
by an interpreterType commands into interpreter and see
immediate results
Computer
RuntimeEnvironmentCompilerCodeJava:
ComputerInterpreterCodeRuby:
What is Ruby on Rails (RoR)Development framework for web
applications written in Ruby Used by some of your favorite sites!
Advantages of a frameworkStandard features/functionality are built-inPredictable application organization
Easier to maintainEasier to get things going
InstallationWindows
Navigate to: http://www.ruby-lang.org/en/downloads/
Scroll down to "Ruby on Windows"Download the "One-click Installer"Follow the install instructions
Include RubyGems if possible (this will be necessary for Rails installation later)
Mac/LinuxOS X 10.4 ships with broken Ruby! Go here…
http://hivelogic.com/articles/view/ruby-rails-mongrel-mysql-osx
hello_world.rb
puts "hello world!"
All source code files end with .rb = ruby
NOTE: we are not really going to learn how to make general ruby programs but, in this class we will learn about Ruby on Rails ---which is a web framework for making web apps or web sites.
puts vs. print"puts" adds a new line after it is done analogous System.out.println()
"print" does not add a new lineanalogous to System.out.print()
Running Ruby Programs (via interpreter)Use the Ruby interpreter
ruby hello_world.rb“ruby” tells the computer to use the Ruby interpreter
Interactive Ruby (irb) consoleirb
Get immediate feedbackTest Ruby features
NOTE: we are not really going to learn how to make general ruby programs but, in this class we will learn about Ruby on Rails ---which is a web framework for making web apps or web sites.
Comments# this is a single line comment
=beginthis is a multiline commentnothing in here will be part of the code
=end
Variables
Declaration – No need to declare a "type"
Assignment – same as in JavaExample: (like javascript)
x = "hello world" # Stringy = 3 # Fixnumz = 4.5 # Floatr = 1..10 # Range
Variable Names and Scopesfoo Local variable$foo Global variable@foo Instance variable in object@@foo Class variableMAX_USERS “Constant” (by convention)
Difference between instance and “class” variables
Instance variables are scoped within a specific instance.
instance variable title, each post object will have its own title.
Class variables , instead, is shared across all instances of that class.
class Post def initialize(title) @title = title end
def title @title endend
p1 = Post.new("First post")p2 = Post.new("Second post")
p1.title# => "First post"p2.title# => "Second post"
class Post @@blog = "The blog“
# previous stuff for title here…….
def blog @@blog end
def blog=(value) @@blog = value endend
p1.blog# => "The blog"p2.blog# => "The blog“p1.blog = "New blog" p1.blog # => "New blog"p2.blog # => "New blog"
ObjectsEverything is an object.
Common Types (Classes): Numbers, Strings, Ranges
nil, Ruby's equivalent of null is also an object
Uses "dot-notation" like Java objectsYou can find the class of any variable
x = "hello"x.class String
You can find the methods of any variable or class
x = "hello"x.methodsString.methods
String Literals“How are you today?”
Single quotes (only \' and \\)'Bill\'s "personal" book'
Double quotes (many escape sequences)"Found #{count} errors\nAborting job\n"
%q (similar to single quotes)%q<Nesting works: <b>Hello</b>>
%Q (similar to double quotes)%Q|She said "#{greeting}"\n|
“Here documents”<<ENDFirst lineSecond lineEND
Ruby String Syntax
Equalities
x = Array.new # how to declare an arrayx << 10x[0] = 99y = ["Alice", 23, 7.3]x[1] = y[1] + y[-1]
ary = Array.new #sets to empty array [] Array.new(3) #sets to length of 3 [nil, nil, nil] Array.new(3, true) #sets to length of 3 [true, true, true]
person = Hash.newperson["last_name"] = "Rodriguez"person[:first_name] = "Alice“
order = {"item" => "Corn Flakes", "weight" => 18}order = {:item => "Corn Flakes", :weight => 18}order = {item: "Corn Flakes", weight: 18}
Arrays and Hashes
Hashes – Starting the Zombies exampleFrom http://railsforzombies.org/
Arrays ---accessing elementsarr = [1, 2, 3, 4, 5, 6] arr[2] # 3 arr[100] # nil arr[-3] # 4 arr[2, 3] # [3, 4, 5] –means start index 2 and get 3 elements
arr[1..4] # [2, 3, 4, 5] –means start index 1 through 4 index
Also, arr.first and arr.last
array = [14, 22, 34, 46, 92]for value in array do ...end
Objects (cont.)There are many methods that all Objects
haveInclude the "?" in the method names, it is
a Ruby naming convention for boolean methods
nil?eql?/equal? (3.eql?2)==, !=, ===instance_of?is_a?to_s
NumbersNumbers are objectsDifferent Classes of Numbers
FixNum, Float3.eql?2 false-42.abs 423.4.round 33.6.round 43.2.ceil 43.8.floor 33.zero? false
Booleannil or false = falseEverything else = true
String Methods"hello world".length 11
"hello world".nil? false
"".nil? false
"ryan" > "kelly" true
"hello_world!".instance_of?String true
"hello" * 3 "hellohellohello"
"hello" + " world" "hello world"
"hello world".index("w") 6
Operators and LogicSame as Java
* , / , +, - Also same as Java
"and" and "or" as well as "&&" and "||"Strings
String concatenation (+)String multiplication (*)
Conditionals: if/elsif/else/endMust use "elsif" instead of "else if"Notice use of "end". It replaces closing
curly braces in JavaExample:
if (age < 35)puts "young whipper-snapper"
elsif (age < 105)puts "80 is the new 30!"
elseputs "wow… gratz..."
end
Inline "if" statementsOriginal if-statement
if age < 105puts "don't worry, you are still young"
end
Inline if-statementputs "don't worry, you are still young" if age < 105
Case Statementsgrade = case score when 0..60: ‘F’ when 61..70: ‘D’ when 71..80: ‘C’ when 81..90: ‘B’ when 90..100: ‘A’end
for-loops for-loops can use ranges Example 1:
for i in 1..10puts i
end
for-loops and rangesYou may need a more advanced range for your for-loop
Bounds of a range can be expressions
Example:for i in 1..(2*5)
puts iend
Out of blocks or loops: break, redo, next, retry
while-loops
Cannot use "i++"Example:
i = 0while i < 5
puts ii = i + 1
end
Example little routine
sum = 0i = 1while i <= 10 do sum += i*i i = i + 1endputs "Sum of squares is #{sum}\n"
Newline is statement separator
do ... end instead of { ... }
Optional parenthesesin method invocation
Substitution instring value
No variable declarations
unless"unless" is the logical opposite of "if"
Example:unless (age >= 105) # if (age < 105)puts "young."
elseputs "old."
end
untilSimilarly, "until" is the logical opposite
of "while"Can specify a condition to have the
loop stop (instead of continuing)Example
i = 0until (i >= 5) # while (i < 5), parenthesis not required
puts Ii = i + 1
end
MethodsStructure
def method_name( parameter1, parameter2, …)
statementsend
Simple Example:def print_ryan
puts "Ryan"end
ParametersNo class/type required, just name
them!Example:
def cumulative_sum(num1, num2)sum = 0for i in num1..num2
sum = sum + iendreturn sum
end
# call the method and print the resultputs(cumulative_sum(1,5))
ReturnRuby methods return the value of
the last statement in the method, so…
def add(num1, num2)sum = num1 + num2return sum
end
can becomedef add(num1, num2)
num1 + num2end
Method with array as parameterdef max(first, *rest) result= first for x in rest do if (x > result) then result= x end end return resultend
Modules – require one .rb file into another
Modules: Grouping of methods, classes, constants that make sense together…a bit like a library
User Input"gets" method obtains input from a
userExample
name = getsputs "hello " + name + "!"
Use chomp to get rid of the extra lineputs "hello" + name.chomp + "!"
chomp removes trailing new lines
Changing typesYou may want to treat a String a
number or a number as a Stringto_i – converts to an integer (FixNum)to_f – converts a String to a Floatto_s – converts a number to a String
Examples"3.5".to_i 3"3.5".to_f 3.53.to_s "3"
ConstantsIn Ruby, constants begin with an
UppercaseThey should be assigned a value at most
onceThis is why local variables begin with a
lowercaseExample:
Width = 5def square
puts ("*" * Width + "\n") * Widthend
Handling Exceptions: Catch Throw
def sample # a silly method that throws and exception x=1 throw :foo if x==1end
begin puts ‘start’ sample # call above method puts ‘end’rescue puts ‘exception found’end
General format of handling exceptions
begin
# - code that could cause exception
rescue OneTypeOfException
# - code to run if OneTypeException
rescue AnotherTypeOfException
# - code to run if AnotherTypeOfException
else
# code to run for Other exceptions
end
Classes
Slide 46
Simple Classclass Point def initialize(x, y) @x = x @y = y end def x #defining class variable
@x end def x=(value) @x = value endend
#code using class
p = Point.new(3,4)puts "p.x is #{p.x}"p.x = 44
Another class - Bookclass Book def initialize(title, author, date) @title = title #various variables @author = author @date = date end def to_s #method to make string "Book: #@title by #{@author} on #{@date}" endend
Book class—adding methods to access class variables (setter/getter)class Book def initialize(title, author, date) # constructor @title = title @author = author @date = date end def author #method to access class variable author @author end def author=(new_author) #method to set value of class variable author @author = new_author endend
Class Inheritance (calling parent-super)
class Book def initialize(title, author, date) @title = title @author = author @date = date end def to_s "Book: #@title by #{@author} on #{@date}" endend
class ElectronicBook < Book def initialize(title, author, date, format) super(title, author, date) @format = format end def to_s super + " in #{@format}" endend
Protection Types –here for methos
class Foo def method1 end def method2 end .... public :method1, method3 protected :method2 private :method4, method5end
Public Methods: Public methods can be called by anyone. Methods are public by default except for initialize, which is always private.
Private Methods: Private methods cannot be accessed, or even viewed from outside the class. Only the class methods can access private members.
Protected Methods: A protected method can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
Creating a method operator called <(w/test class showing using it)
class Book
attr_reader :title
def initialize(title, author, date)
@title = title
@author = author
@date = date
end
def <(book)
return false if book.kind_of(Book)
title < book.title
end
end
require 'test/unit'require 'book' class TestExample < Test::Unit::TestCase def test_operator cat = Book.new("Cat", "Me", "1990") dog = Book.new("Dog", "Me", "1990") assert( cat < dog) endend
File I/O file = File.open('testFile')
while line = file.gets
puts line
end
file.close
File.open('testFile') do |file|
while line = file.gets
puts line
end
end
File.open('testFile') do |file|
file.each_line {|line| puts line}
end
IO.foreach('testFile') {|line| puts line}
puts IO.readlines('testFile')
array = IO.readlines('testFile')
r read-only, start at beginning of file
r+ read/write, start at beginning of file
w write-only, start at beginning of file
w+ read/write, start at beginning of file
a write-only, append to end of file
a+ read/write, start at end of file
b Binary mode, Windows only, combine with above
mode = 'a'
File.open('testFile', mode) do |file|
file.print 'cat'
file.puts 'dog'
file.puts 5
end
File.open('testFile', mode) do |file|
file << 'cat' << "dog\n" << 5 << "\n"
end
Threadsrequire 'net/http'
pages = %w{ www.yahoo.com www.google.com slashdot.org}
threads = []
for page_to_fetch in pages
threads << Thread.new(page_to_fetch) do |url|
browser = Net::HTTP.new(url, 80)
puts "Fetching #{url}"
response = browser.get('/', nil)
puts "Got #{url}: #{response.message}"
end
end
threads.each {|thread| thread.join }
Fetching www.yahoo.com Fetching www.google.comFetching slashdot.org
Got www.yahoo.com: OKGot www.google.com: OKGot slashdot.org: OK
Note: Thread and HTTP are classes in ruby
NOTE: General code to create thread & associate running code (do block) and join it to thread pool
thread = Thread.new do #code to execute in Thread running end
thread.join
ReferencesWeb Sites
http://www.ruby-lang.org/en/ http://rubyonrails.org/
BooksProgramming Ruby: The Pragmatic
Programmers' Guide (http://www.rubycentral.com/book/)
Agile Web Development with RailsRails RecipesAdvanced Rails Recipes