Intro to Ruby
Download
Report
Transcript Intro to Ruby
Ruby
What is Ruby?
Programming Language
Object-oriented
Interpreted
Popular- Ruby on Rails a framework for Web Server
Programming
Interpreted Languages
Not compiled like Java
Code is written and then directly executed by an
interpreter
Type commands into interpreter and see immediate results
Java:
Ruby:
Code
Compiler
Code
Runtime
Environment
Computer
Interpreter
Computer
What is Ruby on Rails (RoR)
Development framework for web applications written in
Ruby
Used by some of your favorite sites!
Advantages of a framework
Standard features/functionality are built-in
Predictable application organization
Easier to maintain
Easier to get things going
Installation
Windows
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/Linux
OS 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 line
analogous 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) console NOTE: we are not
really going to learn
how to make general
irb
ruby programs but, in
this class we will learn
Get immediate feedback
about Ruby on Rails --which is a web
Test Ruby features
framework for making
web apps or web sites.
Comments
# this is a single line comment
=begin
this is a multiline comment
nothing in here will be part of the
code
=end
Variables
Declaration – No need to declare a "type"
Assignment – same as in Java
Example: (like javascript)
x = "hello world"
y=3
z = 4.5
r = 1..10
# String
# Fixnum
# Float
# Range
Variable Names and Scopes
foo
$foo
@foo
@@foo
MAX_USERS
Local variable
Global variable
Instance variable in object
Class variable
“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
end
end
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
end
end
p1.blog
# => "The blog"
p2.blog
# => "The blog“
p1.blog = "New blog"
p1.blog
# => "New blog"
p2.blog
# => "New blog"
Objects
Everything is an object.
Common Types (Classes): Numbers, Strings,
Ranges
nil, Ruby's equivalent of null is also an object
Uses "dot-notation" like Java objects
You 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.methods
String.methods
String Literals
“How are you today?”
Ruby String Syntax
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”
<<END
First line
Second line
END
Equalities
Arrays and Hashes
x = Array.new
# how to declare an array
x << 10
x[0] = 99
y = ["Alice", 23, 7.3]
x[1] = y[1] + y[-1]
ary = Array.new
Array.new(3)
Array.new(3, true)
#sets to empty array []
#sets to length of 3 [nil, nil, nil]
#sets to length of 3 [true, true, true]
person = Hash.new
person["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}
Hashes – Starting the Zombies
example
From http://railsforzombies.org/
Arrays ---accessing elements
arr = [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 have
Include 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
Numbers
Numbers are objects
Different Classes of Numbers
FixNum, Float
3.eql?2
-42.abs
3.4.round
3.6.round
3.2.ceil
3.8.floor
3.zero?
false
42
3
4
4
3
false
Boolean
nil or false = false
Everything else = true
String Methods
"hello world".length
11
"hello world".nil?
false
"".nil?
false
"ryan" > "kelly"
true
"hello_world!".instance_of?String
"hello" * 3
"hellohellohello"
"hello" + " world"
"hello world"
"hello world".index("w")
6
true
Operators and Logic
Same as Java
* , / , +, Also same as Java
"and" and "or" as well as "&&" and "||"
Strings
String concatenation (+)
String multiplication (*)
Conditionals: if/elsif/else/end
Must use "elsif" instead of "else if"
Notice use of "end". It replaces closing curly braces in Java
Example:
if (age < 35)
puts "young whipper-snapper"
elsif (age < 105)
puts "80 is the new 30!"
else
puts "wow… gratz..."
end
Inline "if" statements
Original if-statement
if age < 105
puts "don't worry, you are still young"
end
Inline if-statement
puts "don't worry, you are still young" if age < 105
Case Statements
grade = 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..10
puts i
end
for-loops and ranges
You 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 i
end
Out of blocks or loops: break, redo,
next, retry
while-loops
Cannot use "i++"
Example:
i=0
while i < 5
puts i
i=i+1
end
Example little routine
No variable declarations
sum = 0
Newline is statement separator
i = 1
while i <= 10 do
sum += i*i
i = i + 1
do ... end instead of { ... }
end
puts "Sum of squares is #{sum}\n"
Optional parentheses
in method invocation
Substitution in
string value
unless
"unless" is the logical opposite of "if"
Example:
unless (age >= 105)
puts "young."
else
puts "old."
end
# if (age < 105)
until
Similarly, "until" is the logical opposite of
"while"
Can specify a condition to have the loop stop
(instead of continuing)
Example
i=0
until (i >= 5)
required
puts I
i=i+1
end
# while (i < 5), parenthesis not
Methods
Structure
def method_name( parameter1, parameter2, …)
statements
end
Simple Example:
def print_ryan
puts "Ryan"
end
Parameters
No class/type required, just name them!
Example:
def cumulative_sum(num1, num2)
sum = 0
for i in num1..num2
sum = sum + i
end
return sum
end
# call the method and print the result
puts(cumulative_sum(1,5))
Return
Ruby methods return the value of the last
statement in the method, so…
def add(num1, num2)
sum = num1 + num2
return sum
end
can become
def add(num1, num2)
num1 + num2
end
Method with array as parameter
def max(first, *rest)
result= first
for x in rest do
if (x > result) then
result= x
end
end
return result
end
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 user
Example
name = gets
puts "hello " + name + "!"
Use chomp to get rid of the extra line
puts "hello" + name.chomp + "!"
chomp removes trailing new lines
Changing types
You may want to treat a String a number or a
number as a String
to_i – converts to an integer (FixNum)
to_f – converts a String to a Float
to_s – converts a number to a String
Examples
"3.5".to_i
"3.5".to_f
3.to_s
3
3.5
"3"
Constants
In Ruby, constants begin with an Uppercase
They should be assigned a value at most once
This is why local variables begin with a lowercase
Example:
Width = 5
def square
puts ("*" * Width + "\n") * Width
end
Handling Exceptions: Catch Throw
def sample # a silly method that throws and exception
x=1
throw :foo if x==1
OUTPUT
end
start
catch :foo do
puts ‘start’
sample # call above method
puts ‘end’
end
Simple Class
class Point
def initialize(x, y)
@x = x
@y = y
end
def x
@x
end
#defining class variable
def x=(value)
@x = value
end
end
#code using class
p = Point.new(3,4)
puts "p.x is #{p.x}"
Slide 45
p.x = 44
Another class - Book
class Book
def initialize(title, author, date)
@title = title
#various class variables
@author = author
@date = date
end
def to_s
#method to make string
"Book: #@title by #{@author} on #{@date}"
end
end
Book class—adding methods to access
class variables (setter/getter)
class Book
def initialize(title, author, date)
@title = title
@author = author
@date = date
end
def author
@author
end
#method to access class variable author
def author=(new_author)
@author = new_author
end
end
#method to set value of class variable author
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}"
end
end
class ElectronicBook < Book
def initialize(title, author, date, format)
super(title, author, date)
@format = format
end
def to_s
super + " in #{@format}"
end
end
Protection Types –here for methos
class Foo
def method1
end
def method2
end
....
public :method1, method3
protected :method2
private
:method4, method5
end
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
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)
def <(book)
end
return false if book.kind_of(Book) end
title < book.title
end
end
mode = 'a'
File.open('testFile', mode) do |file|
file.print 'cat'
file.puts 'dog'
file.puts 5
end
File I/O
file = File.open('testFile')
while line = file.gets
puts line
end
file.close
File.open('testFile', mode) do |file|
file << 'cat' << "dog\n" << 5 << "\n"
end
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
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
IO.foreach('testFile') {|line| puts line}
a
write-only, append to end of file
puts IO.readlines('testFile')
a+ read/write, start at end of file
array = IO.readlines('testFile')
b
Binary mode, Windows only, combine with above
Threads
require '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.com
Fetching slashdot.org
Got www.yahoo.com: OK
Got www.google.com: OK
Got slashdot.org: OK
References
Web Sites
http://www.ruby-lang.org/en/
http://rubyonrails.org/
Books
Programming Ruby: The Pragmatic Programmers' Guide
(http://www.rubycentral.com/book/)
Agile Web Development with Rails
Rails Recipes
Advanced Rails Recipes