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

From X To Ruby

From X To Ruby

My morning training session at LSRC 2013

Avatar for Anthony Lewis

Anthony Lewis

July 18, 2013
Tweet

More Decks by Anthony Lewis

Other Decks in Programming

Transcript

  1. About Me • Senior Engineer at Mass Relevance • @anthonylewis

    [email protected] • http://anthonylewis.com Thursday, July 18, 13
  2. Session Overview • Installation • Tools • Syntax • Enumerable

    • Classes & Modules Thursday, July 18, 13
  3. Windows • Planning to use Rails? • Use Rails Installer

    • http://railsinstaller.org • Use Ruby Installer • http://rubyinstaller.org Thursday, July 18, 13
  4. Mac OS X • Planning to use Rails? • Use

    Rails Installer • http://railsinstaller.org • Use Homebrew? • brew install ruby • Try RVM Thursday, July 18, 13
  5. Linux • Check your package system • Does it have

    Ruby 1.9 or later? • Enjoy building from source? • Try RVM Thursday, July 18, 13
  6. Ruby Version Manager • For Mac OS X and Linux

    • Install multiple versions of Ruby • Builds from source • Dev Tools Required • http://rvm.io Thursday, July 18, 13
  7. Ruby • A dynamic, open source programming language with a

    focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write. • Created by Yukihiro “Matz” Matsumoto • http://www.ruby-lang.org/en Thursday, July 18, 13
  8. Gem • RubyGems is the ruby packaging system. It provides

    a standard format for distributing Ruby programs and libraries, and an easy to use tool for managing the installation of gem packages. • https://rubygems.org Thursday, July 18, 13
  9. Bundler • Bundler manages an application's dependencies through its entire

    life across many machines systematically and repeatably. • http://gembundler.com Thursday, July 18, 13
  10. Text Editors • The Classics: Emacs, Vim • Cross Platform:

    Sublime Text 2 • http://www.sublimetext.com Thursday, July 18, 13
  11. Interactive Ruby • Open a Command Prompt or Terminal •

    Type “irb” and press Enter Thursday, July 18, 13
  12. Statements • Separated by line breaks • Use semicolons to

    include more than one statement on a line • An operator, comma, or dot followed by a line break continues the current statement • Strings can contain line breaks Thursday, July 18, 13
  13. Numbers & Math irb> 1 + 2 => 3 irb>

    2 * 3 => 6 irb> 6 / 3 => 2 Thursday, July 18, 13
  14. Floating Point Math irb> 6 / 3 => 2 irb>

    7 / 3 => 2 irb> 7.0 / 3 => 2.33333333333333 Thursday, July 18, 13
  15. Strings irb> "Hello" => "Hello" irb> "Hi" + "There" =>

    "HiThere" irb> "Hi" * 3 => "HiHiHi" Thursday, July 18, 13
  16. String Interpolation irb> name = "Tony" => "Tony" irb> "Hi

    #{name}" => "Hi Tony" Thursday, July 18, 13
  17. Symbols • Symbols are used as identifiers in Ruby •

    They are like an immutable string • Use a single memory address irb> :hello => :hello Thursday, July 18, 13
  18. Strings vs Symbols • Jim Weirich says... • If the

    contents of the object are important, use a String. • If the identity of the object is important, use a Symbol. Thursday, July 18, 13
  19. Constants • Name starts with an upper case • Typically

    written in ALL CAPS irb> PI = 3.14 => 3.14 irb> 2 * PI => 6.28 Thursday, July 18, 13
  20. Arrays • A list of objects • Enclosed in square

    brackets irb> list = [1, 2, 3] => [1, 2, 3] irb> list[1] => 2 Thursday, July 18, 13
  21. Hashes • A set of key value pairs • Enclosed

    in curly braces irb> person = {:name => "Tony"} => {:name=>"Tony"} irb> person[:name] => "Tony" Thursday, July 18, 13
  22. Ruby 1.9+ Syntax • Drop the hash rocket • Move

    the colon to the end of the symbol irb> person = {name: "Tony"} => {:name=>"Tony"} irb> person[:name] => "Tony" Thursday, July 18, 13
  23. • if executes code if the condition is true Conditionals

    age = 21 if age < 13 puts "Child" end Thursday, July 18, 13
  24. • Use elsif and else to add more conditions Conditionals

    if age < 13 puts "Child" elsif age < 18 puts "Teenager" else puts "Adult" end Thursday, July 18, 13
  25. • If not name empty, print name Conditionals name =

    "Tony" if !name.empty? puts name end Thursday, July 18, 13
  26. • Unless name empty, print name Conditionals name = "Tony"

    unless name.empty? puts name end Thursday, July 18, 13
  27. • Print name, unless name empty Conditionals name = "Tony"

    puts name unless name.empty? Thursday, July 18, 13
  28. Boolean Logic • Any expression can be treated as a

    boolean • false and nil are considered falsey • All other values are truthy • Use the empty? method to see if a string or collection is empty Thursday, July 18, 13
  29. Iteration • In addition to the standard for and while

    loops in other languages list = [1, 2, 3, 4] list.each do |number| puts number end Thursday, July 18, 13
  30. Blocks • Code passed to and executed by a method

    • A block forms a closure • Local variables are available inside • Surrounded by do ... end or {} • Arguments, if any, go between || Thursday, July 18, 13
  31. Blocks list = [1, 2, 3, 4] x = 2

    list.each do |number| puts x * number end list.each { |n| puts x * n } Thursday, July 18, 13
  32. Blocks • Not just for loops • Pass a block

    to File.open and it will close the file, even on exceptions File.open("test.txt") do |f| puts f.readlines end Thursday, July 18, 13
  33. Methods • A reusable piece of code with a name

    def greet(name = "World") puts "Hello, #{name}" end irb> greet "Hello, World" => nil Thursday, July 18, 13
  34. Enumerable • Module commonly included in collections • Adds traversal

    and other methods • all?, any?, collect, count (map), detect (find), first, include?, inject (reduce), max, min, reject, select, sort, take Thursday, July 18, 13
  35. all? • Returns true if the given block never returns

    false or nil irb> list = [1, 2, 3, 4] irb> list.all? { |n| n.even? } => false Thursday, July 18, 13
  36. any? • Returns true if the given block ever returns

    a value other than false or nil irb> list = [1, 2, 3, 4] irb> list.any? { |n| n.even? } => true Thursday, July 18, 13
  37. collect (map) • Returns a new array with the result

    of running the block on each element irb> list = [1, 2, 3, 4] irb> list.map { |n| n * n } => [1, 4, 9, 16] Thursday, July 18, 13
  38. detect (find) • Returns the first element where the block

    is not false irb> list = [1, 2, 3, 4] irb> list.find { |n| n % 2 == 0 } => 2 Thursday, July 18, 13
  39. first • Returns the first element of the collection irb>

    list = [1, 2, 3, 4] irb> list.first => 1 Thursday, July 18, 13
  40. include? • Returns true if the collection includes the given

    object irb> list = [1, 2, 3, 4] irb> list.include? 3 => true Thursday, July 18, 13
  41. inject (reduce) • Combine all elements into a single object

    using the given starting value and block irb> list = [1, 2, 3, 4] irb> list.reduce(0) do |memo, n| irb> memo + n irb> end => 10 Thursday, July 18, 13
  42. max, min • Returns the element with the maximum or

    minimum value respectively irb> list = [1, 2, 3, 4] irb> list.max => 4 Thursday, July 18, 13
  43. reject • Returns an array of elements where the block

    returns false irb> list = [1, 2, 3, 4] irb> list.reject { |n| n.even? } => [1, 3] Thursday, July 18, 13
  44. select • Returns an array of elements where the block

    returns true irb> list = [1, 2, 3, 4] irb> list.select { |n| n.even? } => [2, 4] Thursday, July 18, 13
  45. sort • Returns a sorted copy of the collection, using

    an optional block irb> list = [1, 2, 3, 4] irb> list.sort { |a,b| b <=> a } => [4, 3, 2, 1] Thursday, July 18, 13
  46. take • Returns the requested number of elements from the

    collection irb> list = [1, 2, 3, 4] irb> list.take 2 => [1, 2] Thursday, July 18, 13
  47. Method Chaining • Combine several methods irb> list.map { |n|

    n ** 3 }. select { |n| n.even? }.first => 8 Thursday, July 18, 13
  48. Dangerous Methods • Modify the collection in place • Method

    names end with an exclamation irb> list = [1, 2, 3, 4] irb> list.select! { |n| n.even? } => [2, 4] Thursday, July 18, 13
  49. Classes • A collection of data and methods class Person

    def initialize(name) @name = name end def greet puts "Hi, I'm #{@name}" end end Thursday, July 18, 13
  50. Classes • Instantiating and using irb> guy = Person.new("Tony") =>

    irb> guy.greet => "Hi, I'm Tony" Thursday, July 18, 13
  51. Instance Variable • A variable that belongs to a specific

    instance of the class • Protected inside the class • Starts with @ • For example, @name in the Person class Thursday, July 18, 13
  52. Instance Variable • Use attr_accessor to make an instance variable

    available outside the class irb> class Person irb> attr_accessor :name irb> end irb> guy.name => "Tony" Thursday, July 18, 13
  53. Instance Method • Methods that are called on a specific

    instance of the class • For example, guy.greet Thursday, July 18, 13
  54. Class Variable • A variable that is shared among all

    instances of the class, and the class itself • Protected inside the class • Starts with @@ Thursday, July 18, 13
  55. Class Method • A method that is called on the

    class itself • For example, Person.new • Many examples in ActiveRecord • Post.all • Comment.where(post_id: 2) Thursday, July 18, 13
  56. Access Modifiers • private - available to instances of the

    class • protected - available to instances of the class and subclasses • public - available to everyone Thursday, July 18, 13
  57. Inheritance • Single inheritance only • Use modules / mixins

    to model multiple inheritance class Student < Person # ... end Thursday, July 18, 13
  58. Modules • Model qualities or abilities of things • Cannot

    be instantiated • Class names are typically nouns • Module names are typically adjectives Thursday, July 18, 13
  59. Modules module Distractible def distract puts "Oh, kittens" end end

    class Student < Person include Distractible end Thursday, July 18, 13
  60. Modules irb> bob = Student.new("Bob") => irb> bob.greet => "Hi,

    I’m Bob" irb> bob.distract => "Oh, kittens" Thursday, July 18, 13
  61. Learn More Ruby • Programming Ruby 1.9 & 2.0 •

    The PickAxe Book • by Dave Thomas, with Chad Fowler and Andy Hunt Thursday, July 18, 13
  62. Learn Onscreen • Try Ruby • http://tryruby.org • Ruby Koans

    • http://rubykoans.com • Ruby has damaged your karma. Thursday, July 18, 13