Ruby on Rails: Introduction to Ruby April 8th, 2015

  • ruby -v to check version
  • Everything in Ruby is an object
  • You don’t declare variable types, but all objects have a type
  • No compiler, so unit testing is crucial
  • No auto type conversion … “3” + 4 results in a TypeError
  • Created in Japan in 1995 by Yukihiro Matsumoto “Mats”
    • Inspired by Pearl and Smalltalk
    • Popular after 2005
  • Run a file from irb … load ‘./hello.rb’
  • IRB = console = Interactive Ruby (you can hookup to your actual app and do stuff to it)
  • The second line is just IRB’s way of telling us the result of the last expression it evaluated
  • def h(name = "World") is how you declare a default value if none is passed to the method
  • #{name} or #{@name} is how you insert the value of a variable into a string
  • @blahblah is an instance variable and available to all the methods of the class
  • Create an object to set a class in motion
  • CLASSNAME.instance_methods to list ALL methods including ancestor methods, or CLASSNAME.instance_methods(false) to exclude ancestor methods
  • Test if your object responds to a method … OBJECTINSTANCENAME.respond_to?(“METHODNAME”)
  • Comments are written as # comment
  • =begin =end (multi-line comment)
  • In Ruby, anything on a line after a hash mark is a comment and is ignored by the interpreter. The first line of the file is a special case, and under a Unix-like operating system tells the shell how to run the file
  • A block is like an anonymous function or lambda. The variable between pipe characters is the parameter for this block.
  • The technique of not caring about the actual type of a variable, just relying on what methods it supports is known as “Duck Typing”, as in “if it walks like a duck and quacks like a duck…”. The benefit of this is that it doesn’t unnecessarily restrict the types of variables that are supported. If someone comes up with a new kind of list class, as long as it implements the join method with the same semantics as other lists, everything will work as planned.
  • if __FILE__ == $0
    

    __FILE__ is the magic variable that contains the name of the current file. $0 is the name of the file used to start the program. This check says “If this is the main file being used…” This allows a file to be used as a library, and not to execute code in that context, but if the file is being used as an executable, then execute that code.

  • Ruby is slower than Java
  • Hash … options = {1=>’a’, ‘foo’=>42}
  • :sort is a symbol
  • nil is an object of type NilClass (true or false)
  • Range … score = 0..100 (two or three dots … one is inclusive and the other is not)
  • You can swap variables without temp assignments
  • Variables must start with lowercase or underscore
  • if, if/else, unless, case-when-when-else-end
  • case VARIABLE … when 20
  • Ternary ? this : else
  • =~ is a regex matcher
  • <=> is the spaceship operator … less than is -1, equals is 0, greater is 1
  • Methods and blocks are used instead of while and for loops
  • Snake Case = this_is_snake_case (use for variables)
  • Camel Case = ThisIsCamelCase (use for class)
  • Why is it Ruby on Rails? … because Rails is a gem which is a library. Gems is the package thingy. (apidock.com)
  • An object is a combination of state (for example, the quantity and the product ID) and methods that use that state (perhaps a method to calculate the line item’s total cost)
  • Objects are created by calling a constructor, a special method associated with a class; the standard constructor is called new()
  • Parentheses are generally optional in method calls
  • Names in Ruby have special rules…
    • Local variables, method parameters, and method names should all start with a lowercase letter or with an underscore and be snake-case … like_this
    • Instance variables begin with ‘@’
    • Class names, module names, and constants must start with an uppercase letter
    • Rails uses symbols to identify things (string literals magically made into constants) and they begin with a ‘:’
      • In particular, it uses them as keys when naming method parameters and looking things up in hashes such as … redirect_to :action => “edit”, :id => params[:id]
      • Alternatively, you can consider the colon to mean “thing named,” so :id is “the thing named id.”
  • Ruby uses end instead of braces to delimit the bodies of compound statements and definitions (such as methods and classes)
  • The keyword return is optional, and if not present, the results of the last expression evaluated will be returned
  • String literals are sequences of characters between single or double quotation marks
    • Ruby does more work to process strings in double quotes
      • First, it substitutes sequences starting with a backslash (e.g. \n is replaced with a newline character)
        • When you write a string containing a newline to the console, the \n forces a line break
      • Second, Ruby performs expression interpolation … #{expression}
  • Array literals … [1, ‘test’, 3.14]
  • nil is an object that represents nothing
    • The method <<() is commonly used with arrays to append a value
  • Ruby has a shortcut for creating an array of words…
    • a = %w{ ant bee cat dog elk } … === … a = [ ‘ant’, ‘bee’, ‘cat’, ‘dog’, ‘elk’ ]
  • Hashes…
    inst_section = {
      :drum => 'percussion',
      :trumpet => 'brass',
      :violin => 'string'
    }
    
    inst_section = {
      drum: 'percussion',
      trumpet: 'brass',
      violin: 'string'
    }
    
  • The following code fragment shows a two-element hash being passed to the redirect_to() method. In effect, though, you can ignore that it’s a hash and pretend that Ruby has keyword arguments…
    redirect_to action: 'show', id: product.id
  • In Ruby, you typically create a regular expression by writing /pattern/ or %r{pattern}
  • Programs typically test strings against regular expressions using the =~ match operator
    if line =~ /P(erl|ython)/
      puts "There seems to be another scripting language here"
    end
    
  • Ruby control structures … if, while, unless, until
    • Ruby statement modifier shortcuts for single expressions… (e.g. puts “Danger, Will Robinson” if radiation > 3000)
    • In Ruby, blocks and iterators are often used in place of looping constructs
      • Braces for single-line blocks and do/end for multiline blocks
      • You can pass a block to a method after any parameters
        • A method can invoke an associated block one or more times using the Ruby yield statement
        • You can pass values to the block by giving parameters to yield
        • Within the block, you list the names of the arguments to receive these parameters between vertical bars (|)
        • The & prefix operator will allow a method to capture a passed block as a named parameter
        • ARRAY.each, N.times
    • Exceptions are objects of class Exception or its subclasses
    • The raise method causes an exception to be raised
    • Both methods and blocks of code wrapped between begin and end keywords intercept certain classes of exceptions using rescue clauses
  • There are two basic concepts in Ruby for organizing methods … classes and modules
    • class Order < ActiveRecord::Base …This Order class is defined to be a subclass of the class Base within the ActiveRecord module
    • Methods making assertions about a class are called declarations (e.g. has_many :line_items)
    • Prefixing a method with self makes it a class method
    • Objects of a class hold their state in instance variables
      • To make instance variables accessible outside of the class, write methods that return their values
        class Greeter
          def initialize(name)
            @name = name
          end
          def name
            @name
          end
          def name=(new_name)
            @name = new_name
          end
        end
        g = Greeter.new("Barney")
        g.name # => Barney
        g.name = "Betty"
        g.name # => Betty
        
        • Ruby provides convenience methods that write these accessor methods for you
          class Greeter
            attr_accessor :name # create reader and writer methods
            attr_reader :greeting # create reader only
            attr_writer :age # create writer only
          end
          
    • The private directive is the strictest; private methods can be called only from within the same instance
    • protected methods can be called both in the same instance and by other instances of the same class and its subclasses
    • Modules can hold a collection of methods, constants, and other module and class definitions
      • You cannot create objects based on modules
      • Modules serve two purposes
        • Namespacing
        • Sharing functionality between classes
      • Helper methods are an example of where Rails uses modules
      • YAML (YAML Ain’t Markup Language) is a module in the standard Ruby library used to define the configuration of things such as databases, test data, and translations
  • Marshaling … Ruby can take an object and convert it into a stream of bytes that can be stored outside the application
  • Ruby method names can end with an exclamation mark (a bang method) or a question mark (a predicate method)
    • Bang methods normally do something destructive to the receiver
    • Predicate methods return true or false depending on some condition
  • a || b … a common way of returning a default value if the first value hasn’t been set
  • count += 1 … assignment statements support shortcuts
  • gets method will prompt user for input
    • Adding the string .chomp method will remove carriage returns (\n , \r , and \r\n)
  • to_string method turns a number into a string (helps when you want to concatenate it with text)

Resources