Ruby101
-
Upload
nola-stowe -
Category
Technology
-
view
156 -
download
0
description
Transcript of Ruby101
Ruby 101
1
Thursday, April 18, 13
Topics
• Ruby Syntax
• Methods/Functions
• DataTypes
• Control Flow
• Exceptions
2
Thursday, April 18, 13
Ruby Syntax
3
Thursday, April 18, 13
Ruby Syntax• indent 2 spaces, no tabs
• CamelCase for class names
• snake_case_for methods and variables
• filenames always snake case
user_setting.rb
class UserSetting def update_from_params(params) end def save endend 4
Thursday, April 18, 13
Ruby Syntax
• comments start with #
• multi-line =begin =end
# one line comment
=begin name = "Bob" address = "123 street" city = "Any Town"=end
5
Thursday, April 18, 13
parentheses optional (mostly!)
need them here
else will an OR here
Document.new "The Ruby Way", "Hal Fulton"Document.new("The Ruby Way", "Hal Fulton")
event_date.to_s :shortevent_date.to_s(:short)
if name.blank? puts "Hi nobody"end
if (name.blank? || (name == "bob"))if name.blank? || (name == "bob")
if name.blank? || name == "bob"
6
Thursday, April 18, 13
one more thing about parentheses
class User def status #blah blah endend
class User def status() #blah blah endend
always
never
7
Thursday, April 18, 13
Variables
8
$global_variable@@class_variable@instance_variableCONSTANT
Thursday, April 18, 13
String Interpolation vs String Concatenation
10.times { |n| puts "the number is #{n}" }
String Interpolation, plus reads better
10.times { |n| puts "the number is" + n }
String concatenation, slow-er!
plus calls to_s if not a string
9
Thursday, April 18, 13
• code style
• variable/class style
• comments
• role of parentheses
• variables
• string interpolation
10
Learned about Ruby Syntax
Thursday, April 18, 13
Methods
11
functions usually called methods
Thursday, April 18, 13
Method Return Values
12
def format_name(user) return "#{user.first.capitalize} #{user.last.capitalize}"end
def format_name(user) "#{user.first.capitalize} #{user.last.capitalize}"end
Last line of function is implicit return
Thursday, April 18, 13
methods with ? !
13
def validate_user?(user) if user.first.present? && user.last.present? true else false end end
def promote_user!(user, level) user.access = level user.saveend
Thursday, April 18, 13
methods with ?
14
> "classified ventures".include?("class") => true> "classified ventures".include?("blah") => false
Use ? as part of the method name if it returns a boolean
Thursday, April 18, 13
Using !
15
> company = "classified ventures" => "classified ventures"
> company.upcase => "CLASSIFIED VENTURES"
> company => "classified ventures"
> company.upcase! => "CLASSIFIED VENTURES" > company => "CLASSIFIED VENTURES"
Thursday, April 18, 13
Learned about
• ! methods
• ? methods
• return value
16
Thursday, April 18, 13
Data Types
Everything is an object
no such idea as “primitives”
17
Thursday, April 18, 13
Strings> company = "Classified Ventures" => "Classified Ventures"
> company.length => 19
> company.reverse => "serutneV deifissalC"
> company.upcase => "CLASSIFIED VENTURES"
> company.start_with?("Class") => true
> company.start_with?("Goo") => false
18
Thursday, April 18, 13
Symbols> :first => :first
> :first.class => Symbol
Commonly used in Hashes
19
Thursday, April 18, 13
Whats the difference?> "hello".object_id => 70312121540820
> "hello".object_id => 70312126306720
> :first.object_id => 32488
> :first.object_id => 32488
20
Thursday, April 18, 13
FixNum, BigNum,Booleans > 1.class => Fixnum > 10000000000000000000000000.class => Bignum
> 3.14.class => Float
> true.class => TrueClass
> false.class => FalseClass
21
Thursday, April 18, 13
Arraysfruits = ['apple', 'orange', 'pear']
fruits = %w(apple orange pear)=> ['apple', 'orange', 'pear']
a = Array.new(5)=> [nil, nil, nil, nil, nil]
a = Array.new(5, "--")=> ["--", "--", "--", "--", "--"]
22
Thursday, April 18, 13
Hashes
default value if key is not found
fruits = {:apple => 5, :orange => 4, :pear => 1}
fruits = { apple: 5, orange: 4, pear: 1 }
fruits[:apple]=> 5
z = {} #default is nila = Hash.new( "--" ) #default is “--”
z[:blah]=> nil
a[:blah]=> "--"
Ruby 1.9
23
Thursday, April 18, 13
Struct
24
Crumb = Struct.new(:name, :value) => Crumb
home = Crumb.new("Home", "/") => #<struct Crumb name="Home", value="/">
home => #<struct Crumb name="Home", value="/">
> home.name=> "Home"
> home.value=> "/"
Thursday, April 18, 13
Ranges
25
> 1..10 => 1..10
> (1..10).class => Range
> (1..10).to_a (creates array) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > (1...10).to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9]
two dots includes end point
three dots does not include end point
Thursday, April 18, 13
Learned about Datatypes• Strings
• Symbols
• FixNum, BigNum
• Booleans
• Array
• Hash
• Struct
• Ranges
26
Thursday, April 18, 13
Practice
• www.rubykoans.com
• http://www.zenspider.com/Languages/Ruby/QuickRef.html
27
Thursday, April 18, 13
Classesclass Document attr_accessor :title, :author, :content def initialize(title, author, content) @title = title @author = author @content = content end end
@var is an instance variableaccess it as @var inside class
28
constructor
Thursday, April 18, 13
attr_accessormakes getters and setters
class Document # setter def title=(title) @title = title end # getter def title @title end
class Document attr_accessor :titleend
same result
also attr_reader and attr_writer29
Thursday, April 18, 13
Example Classclass Document attr_accessor :title, :author def initialize(title, author) @title = title @author = author end
def words @content.split end def self.supported_file_types %w(pdf jpg gif doc) end
end
doc = Document.new("The Ruby Way", "Fulton")doc.wordsDocument.supported_file_types
30
instance method
class method
Thursday, April 18, 13
Learned about
• class constructors
• getters/setters
• instance methods
• static methods
31
Thursday, April 18, 13
Control Flow
32
Thursday, April 18, 13
Code Blocks10.times { |n| puts "the number is #{n}" }
10.times do |n| puts "the number is #{n}" better_for_longer_blocks(n)end
33
item for each iteration is n
Thursday, April 18, 13
if / unlessif not @readonly doc.write(text)end
unless @readonly doc.write(text)end
unless @readonly doc.write(text)else log.warn("attempt to write to readonly file")end
doc.write(text) unless @readonly
bad
good
good
bad
34
Thursday, April 18, 13
for / eachfruits = ['apple', 'orange', 'pear']
for fruit in fruits puts fruitend
fruits.each do |fruit| puts fruitend
bad
good
35
Thursday, April 18, 13
while loops
36
i = 0while i < 5 puts i i += 1end
i = 0until i == 5 puts i i += 1end
puts i += 1 until i == 5
Thursday, April 18, 13
Exceptions
37
class Name # Define default getter method, but not setter method. attr_reader :first # When someone tries to set a first name, enforce rules about it. def first=(first) if first.blank? raise ArgumentError.new('Everyone must have a first name.') end @first = first.capitalize endend
def edit name = Name.new name.first = params[:name]rescue ArgumentError => e log.error("Validation Error #{e.message}")end
Thursday, April 18, 13
Covered Control Flow
• if/unless
• for/each
• while loops
• exceptions
38
Thursday, April 18, 13