Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Getting Started with Ruby

Getting Started with Ruby

Some quick tips to getting started with Ruby. Presented at Motorola Solutions' APPFORUM Americas 2012 in Schaumburg, IL.

Daniel Morrison

June 06, 2012
Tweet

More Decks by Daniel Morrison

Other Decks in Programming

Transcript

  1. View Slide

  2. RUBY
    Getting Started
    DANIEL MORRISON Ι COLLECTIVE IDEA
    APPFORUM Americas 2012

    View Slide

  3. WELCOME
    Daniel Morrison
    • @danielmorrison
    • Founder, Collective Idea
    • Based in Holland, Michigan
    • Programmer
    • Ruby & Rails Instructor

    View Slide

  4. RUBY
    Language
    • Dynamic
    • Object-Oriented
    • Designed for Programmer Productivity
    Ruby on Rails
    • Web Framework
    • Launched Ruby into the public eye
    • Inspiration for many other frameworks
    RhoMobile
    • Uses Ruby to bridge devices
    • Rhodes framework takes cues from Rails

    View Slide

  5. CORE
    RUBY

    View Slide

  6. DATA TYPES
    Numbers
    • Integer types:
    • 5.class #=> Fixnum
    • 9999999999999999999.class # => Bignum

    View Slide

  7. DATA TYPES
    Numbers
    • Integer types:
    • 5.class #=> Fixnum
    • 9999999999999999999.class # => Bignum
    Arithmetic Operation
    • + add
    • - subtract
    • * multiply
    • / divide
    • % modulus
    • ** exponent

    View Slide

  8. STRINGS
    Strings in ruby
    • “Hello World”
    • Can use single or double quoted.
    • As well as more esoteric syntaxes: %q|Hello World|

    View Slide

  9. STRINGS
    Strings in ruby
    • “Hello World”
    • Can use single or double quoted.
    • As well as more esoteric syntaxes: %q|Hello World|
    String Interpolation
    • “There are #{24 * 7} hours in a week.”
    • Only works with double quotes.

    View Slide

  10. METHODS

    View Slide

  11. METHODS
    Methods in ruby
    • Called Functions in other languages
    Define and call
    • def my_addition(value1, value2)
    value1 + value2
    end
    • my_add(10, 5) # => 15

    View Slide

  12. VARIABLES

    View Slide

  13. VARIABLES
    Define a variable
    • a = “Hello World”
    • No need to specify type
    • Can redefine at any time
    • a = 15

    View Slide

  14. VARIABLES
    Define a variable
    • a = “Hello World”
    • No need to specify type
    • Can redefine at any time
    • a = 15
    Strong Dynamic Typing
    • Strong: variable always has an explicit type
    • Dynamic: type can change at any time

    View Slide

  15. VARIABLES
    Define a variable
    • a = “Hello World”
    • No need to specify type
    • Can redefine at any time
    • a = 15
    Strong Dynamic Typing
    • Strong: variable always has an explicit type
    • Dynamic: type can change at any time
    Duck Typing
    • def my_addition(value1, value2)
    value1 + value2
    end
    • my_addition(“Hello”, “World”) # => “HelloWorld”

    View Slide

  16. COLLECTION
    DATA TYPES

    View Slide

  17. ARRAY
    Easy to create
    • a = [5, 10, 45, 9]
    • a = Array.new(5, 10, 45, 9) # works, but not usually used.

    View Slide

  18. ARRAY
    Easy to create
    • a = [5, 10, 45, 9]
    • a = Array.new(5, 10, 45, 9) # works, but not usually used.
    Easy to access & modify
    • a[2] # => 45
    • a[0] = 1000 # => [1000, 10, 45, 9]

    View Slide

  19. ARRAY
    Easy to create
    • a = [5, 10, 45, 9]
    • a = Array.new(5, 10, 45, 9) # works, but not usually used.
    Easy to access & modify
    • a[2] # => 45
    • a[0] = 1000 # => [1000, 10, 45, 9]
    Polyglot
    • b = [“banana”, 3.14, -200, “Hello World”]
    • Mix & match values

    View Slide

  20. ARRAY
    Easy to create
    • a = [5, 10, 45, 9]
    • a = Array.new(5, 10, 45, 9) # works, but not usually used.
    Easy to access & modify
    • a[2] # => 45
    • a[0] = 1000 # => [1000, 10, 45, 9]
    Polyglot
    • b = [“banana”, 3.14, -200, “Hello World”]
    • Mix & match values
    Dynamically Sized
    • fruits = [“Apple”, “Banana”]
    • fruits[2] = “Orange” # => [“Apple”, “Banana”, “Orange]
    • fruits.length # => 3

    View Slide

  21. HASH
    Key-Value Store
    • AKA: HashTable, Dictionary, associative array
    • Key is unique

    View Slide

  22. HASH
    Key-Value Store
    • AKA: HashTable, Dictionary, associative array
    • Key is unique
    Easy to Create
    • h = {“name” => “Daniel”, “language” => “Ruby”}

    View Slide

  23. HASH
    Key-Value Store
    • AKA: HashTable, Dictionary, associative array
    • Key is unique
    Easy to Create
    • h = {“name” => “Daniel”, “language” => “Ruby”}
    Easy to Access
    • Array-like syntax
    • h[“name”] # => “Daniel”
    • h[“age”] # => nil
    • h[“age”] = 10 # => {“name” => “Daniel”, “age => 10, “language” => “Ruby”}

    View Slide

  24. HASH
    Key-Value Store
    • AKA: HashTable, Dictionary, associative array
    • Key is unique
    Easy to Create
    • h = {“name” => “Daniel”, “language” => “Ruby”}
    Easy to Access
    • Array-like syntax
    • h[“name”] # => “Daniel”
    • h[“age”] # => nil
    • h[“age”] = 10 # => {“name” => “Daniel”, “age => 10, “language” => “Ruby”}
    Symbols
    • Begin with a colon
    • Most often used as hash keys
    • h = {:name => “Alice”, :age => 10}
    • h[:age] # => 10
    • h[“age”] # => nil

    View Slide

  25. NESTING
    Both Hash & Array can contain each other
    • apple = {“name” => “Apple”, “colors” => [“red”, “green”]}
    • banana = {“name” => “Banana”, “colors” => [“yellow”]}
    • fruits = [apple, banana]
    • fruits.last # => {“name” => “Banana”, “colors” => [“yellow”]}

    View Slide

  26. NESTING
    Both Hash & Array can contain each other
    • apple = {“name” => “Apple”, “colors” => [“red”, “green”]}
    • banana = {“name” => “Banana”, “colors” => [“yellow”]}
    • fruits = [apple, banana]
    • fruits.last # => {“name” => “Banana”, “colors” => [“yellow”]}
    Multidimensional Arrays
    • matrix = [[3, 2, 6], [1, 4, 5], [7, 4, 7]]
    • matrix[0] # => [3, 2, 6]

    View Slide

  27. RANGE
    Ranges of values
    • r = (10..100)
    • r.include?(20) # => true
    • r.include?(2) # => false

    View Slide

  28. RANGE
    Ranges of values
    • r = (10..100)
    • r.include?(20) # => true
    • r.include?(2) # => false
    Useful with Dates & Times
    • jan1 = Date.new(2012, 1, 1)
    • dec31 = Date.new(2012, 1, 1)
    • (jan1..dec31).include?(Date.today) # => true
    • (jan1..dec31).include?(Date.today + 365) # => false

    View Slide

  29. REGULAR
    EXPRESSIONS

    View Slide

  30. REGULAR EXPRESSIONS
    Easy to Create
    • r = Regexp.new(“\d\d\d\d-\d\d-\d\d”)
    • r = /\d\d\d\d-\d\d-\d\d/

    View Slide

  31. REGULAR EXPRESSIONS
    Easy to Create
    • r = Regexp.new(“\d\d\d\d-\d\d-\d\d”)
    • r = /\d\d\d\d-\d\d-\d\d/
    Match Strings
    • info = “Conference runs from 2012-06-04 to 2012-06-06”
    • Use =~ to find match location
    • info =~ /\d\d\d\d-\d\d-\d\d/ # => 21
    • Use match to get the data back
    • info.match(/\d\d\d\d-\d\d-\d\d/) # => #

    View Slide

  32. REGULAR EXPRESSIONS
    Easy to Create
    • r = Regexp.new(“\d\d\d\d-\d\d-\d\d”)
    • r = /\d\d\d\d-\d\d-\d\d/
    Match Strings
    • info = “Conference runs from 2012-06-04 to 2012-06-06”
    • Use =~ to find match location
    • info =~ /\d\d\d\d-\d\d-\d\d/ # => 21
    • Use match to get the data back
    • info.match(/\d\d\d\d-\d\d-\d\d/) # => #
    Substitutions
    • info.sub(/\d\d\d\d-\d\d-\d\d/, “today”)
    - #=> “Conference runs from today to 2012-06-06”
    • info.gsub(/\d\d\d\d-\d\d-\d\d/, “today”)
    - #=> “Conference runs from today to today”

    View Slide

  33. REGULAR EXPRESSIONS
    Test with rubular.com

    View Slide

  34. CONDITIONALS
    AND LOOPS

    View Slide

  35. IF STATEMENTS
    if
    • if input == “quit”
    exit
    end

    View Slide

  36. IF STATEMENTS
    if
    • if input == “quit”
    exit
    end
    Single line if
    • exit if input == “quit”

    View Slide

  37. IF STATEMENTS
    if
    • if input == “quit”
    exit
    end
    Single line if
    • exit if input == “quit”
    unless
    • unless input == “quit”
    do_work
    end
    • do_work unless input == “quit”

    View Slide

  38. ELSE
    Test multiple conditions
    • if input == “quit”
    exit
    elsif input == “pause”
    sleep 20
    else
    do_work
    end

    View Slide

  39. ELSE
    Test multiple conditions
    • if input == “quit”
    exit
    elsif input == “pause”
    sleep 20
    else
    do_work
    end
    • Note the spelling of elsif

    View Slide

  40. CASE
    Ruby’s powerful case statement
    • case input
    when “quit”
    exit
    when “pause”
    sleep 20
    when String
    puts “The input is #{input}”
    when 5..10
    puts “The input was between 5 and 10”
    when /\d\d\d\d-\d\d-\d\d/
    puts “The input looks like a date”
    else
    puts “I don’t understand you.”
    end

    View Slide

  41. WHILE
    Simple while loop
    • count = 0
    • while count < 10
    • puts count
    • count += 1
    • end

    View Slide

  42. WHILE
    Simple while loop
    • count = 0
    • while count < 10
    • puts count
    • count += 1
    • end
    +=
    • Equivalent to count = count + 1
    • Can be used with any number
    • And all basic math operations (*=, -=, etc.)

    View Slide

  43. WHILE
    Simple while loop
    • count = 0
    • while count < 10
    • puts count
    • count += 1
    • end
    +=
    • Equivalent to count = count + 1
    • Can be used with any number
    • And all basic math operations (*=, -=, etc.)
    Inline while
    • count = 0
    • puts count += 1 while count < 10

    View Slide

  44. UNLESS
    Unless is the inverted while
    • count = 0
    • unless count >= 10
    • puts count
    • count += 1
    • end

    View Slide

  45. UNTIL
    until is the inverted while
    • count = 0
    • until count >= 10
    • puts count
    • count += 1
    • end
    Inline until
    • count = 0
    • puts count += 1 until count >= 10

    View Slide

  46. FOR
    For exists in Ruby
    • for fruit in fruits
    • puts “I love #{fruit}
    • end

    View Slide

  47. FOR
    For exists in Ruby
    • for fruit in fruits
    • puts “I love #{fruit}
    • end
    But we don’t use it.

    View Slide

  48. ITERATION
    THE RUBY WAY

    View Slide

  49. EACH
    Use each for iterating
    • fruits.each do |fruit|
    • puts “I love #{fruit}”
    • end

    View Slide

  50. EACH
    Use each for iterating
    • fruits.each do |fruit|
    • puts “I love #{fruit}”
    • end
    Use do & end for multi-line, {} for single-line
    • fruits.each {|fruit| puts “I love #{fruit}” }

    View Slide

  51. EACH
    Use each for iterating
    • fruits.each do |fruit|
    • puts “I love #{fruit}”
    • end
    Use do & end for multi-line, {} for single-line
    • fruits.each {|fruit| puts “I love #{fruit}” }
    Same syntax works for other forms of iterating
    • .map
    • .each_with_index
    • .each_key

    View Slide

  52. OBJECTS

    View Slide

  53. OBJECTS
    Objects
    • class Person
    end

    View Slide

  54. OBJECTS
    Objects
    • class Person
    end
    Inheritance
    • class Programmer < Person
    end

    View Slide

  55. OBJECTS
    Objects
    • class Person
    end
    Inheritance
    • class Programmer < Person
    end
    Constructors
    • class Person
    def initialize(name)
    @name = name
    end
    end

    View Slide

  56. RUBY ON RAILS

    View Slide

  57. RUBY ON RAILS
    What is Rails
    • Web Framework
    • Convention over Configuration
    • Geared toward database-backed
    web applications
    • Great for producing APIS

    View Slide

  58. EXAMPLE RAILS APP
    Demo time!
    • rails new demo
    • cd demo
    • rails generate scaffold person name:string age:integer
    • rails server

    View Slide

  59. USING
    JSON

    View Slide

  60. PARSING JSON
    In Rails
    • JSON.parse(json)
    Rhodes
    • Rho::JSON.parse(json)

    View Slide

  61. PARSING JSON
    In Rails
    • JSON.parse(json)
    Rhodes
    • Rho::JSON.parse(json)
    Both turn JSON into a Hash
    • {
    "name": "Bob",
    "age": 20,
    "friends": ["Alice", "Carol", "Dave"]
    }
    • {
    "name" => "Bob",
    "age" => 20,
    "friends" => ["Alice", "Carol", "Dave"]
    }

    View Slide

  62. XML IN RUBY
    XML is as easy as JSON
    • REXML::Document.new(xml_file)

    View Slide

  63. IRB
    INTERACTIVE RUBY

    View Slide

  64. IRB
    Command-line Ruby
    • irb
    • rails console

    View Slide

  65. IRB
    Command-line Ruby
    • irb
    • rails console
    Inspect data
    • puts x
    • x.inspect

    View Slide

  66. DEBUGGING
    Ruby Debugger
    • debugger gem, or ruby-debug
    • Both work similar to gdb

    View Slide

  67. DEBUGGING
    Read the Errors
    • They tell you line numbers
    NameError: undefined local variable or method `my_method' for #0x007fef2bc51ee0>
    from /Users/daniel/.rvm/gems/[email protected] project/gems/
    activerecord-3.2.2/lib/active_record/dynamic_matchers.rb:50:in
    `method_missing'
    from /Users/daniel/Projects/my_project/app/models/sign.rb:16:in `import'
    from (irb):4
    from /Users/daniel/.rvm/gems/[email protected]/gems/railties-3.2.2/lib/
    rails/commands/console.rb:47:in `start'
    from /Users/daniel/.rvm/gems/[email protected] project/gems/railties-3.2.2/lib/
    rails/commands/console.rb:8:in `start'
    from /Users/daniel/.rvm/gems/[email protected] project/gems/railties-3.2.2/lib/
    rails/commands.rb:41:in `'
    from script/rails:6:in `require'
    from script/rails:6:in `'

    View Slide

  68. DEBUGGING
    Read the Errors
    • They tell you line numbers
    NameError: undefined local variable or method `my_method' for #0x007fef2bc51ee0>
    from /Users/daniel/.rvm/gems/[email protected] project/gems/
    activerecord-3.2.2/lib/active_record/dynamic_matchers.rb:50:in
    `method_missing'
    from /Users/daniel/Projects/my_project/app/models/sign.rb:16:in `import'
    from (irb):4
    from /Users/daniel/.rvm/gems/[email protected]/gems/railties-3.2.2/lib/
    rails/commands/console.rb:47:in `start'
    from /Users/daniel/.rvm/gems/[email protected] project/gems/railties-3.2.2/lib/
    rails/commands/console.rb:8:in `start'
    from /Users/daniel/.rvm/gems/[email protected] project/gems/railties-3.2.2/lib/
    rails/commands.rb:41:in `'
    from script/rails:6:in `require'
    from script/rails:6:in `'

    View Slide

  69. DEBUGGING
    Read the Errors
    • They tell you line numbers
    NameError: undefined local variable or method `my_method' for #0x007fef2bc51ee0>
    from /Users/daniel/.rvm/gems/[email protected] project/gems/
    activerecord-3.2.2/lib/active_record/dynamic_matchers.rb:50:in
    `method_missing'
    from /Users/daniel/Projects/my_project/app/models/sign.rb:16:in `import'
    from (irb):4
    from /Users/daniel/.rvm/gems/[email protected]/gems/railties-3.2.2/lib/
    rails/commands/console.rb:47:in `start'
    from /Users/daniel/.rvm/gems/[email protected] project/gems/railties-3.2.2/lib/
    rails/commands/console.rb:8:in `start'
    from /Users/daniel/.rvm/gems/[email protected] project/gems/railties-3.2.2/lib/
    rails/commands.rb:41:in `'
    from script/rails:6:in `require'
    from script/rails:6:in `'

    View Slide

  70. DEBUGGING
    Read the Errors
    • They sometimes confuse you

    View Slide

  71. DEBUGGING
    Read the Errors
    • They sometimes confuse you
    @user.first_name

    View Slide

  72. DEBUGGING
    Read the Errors
    • They sometimes confuse you
    @user.first_name
    NoMethodError: undefined method `first_name' for nil:NilClass
    from (irb):1
    from /Users/daniel/.rvm/gems/[email protected]/gems/railties-3.2.2/
    lib/rails/commands/console.rb:47:in `start'
    from /Users/daniel/.rvm/gems/[email protected]/gems/railties-3.2.2/
    lib/rails/commands/console.rb:8:in `start'
    from /Users/daniel/.rvm/gems/[email protected]/gems/railties-3.2.2/
    lib/rails/commands.rb:41:in `'
    from script/rails:6:in `require'
    from script/rails:6:in `'

    View Slide

  73. DEBUGGING
    Read the Errors
    • They sometimes confuse you
    @user.first_name
    NoMethodError: undefined method `first_name' for nil:NilClass
    from (irb):1
    from /Users/daniel/.rvm/gems/[email protected]/gems/railties-3.2.2/
    lib/rails/commands/console.rb:47:in `start'
    from /Users/daniel/.rvm/gems/[email protected]/gems/railties-3.2.2/
    lib/rails/commands/console.rb:8:in `start'
    from /Users/daniel/.rvm/gems/[email protected]/gems/railties-3.2.2/
    lib/rails/commands.rb:41:in `'
    from script/rails:6:in `require'
    from script/rails:6:in `'

    View Slide

  74. LEARN MORE

    View Slide

  75. LEARN MORE
    Documentation
    • http://ruby-doc.org
    • http://api.rubyonrails.org
    TryRuby
    • http://tryruby.org
    This Presentation
    • https://speakerdeck.com/u/danielmorrison
    • or shorter URL: http://bit.ly/LqCinu
    Talk to Me
    • @danielmorrison
    • http://collectiveidea.com

    View Slide

  76. View Slide