Pro Yearly is on sale from $80 to $50! »

A Quick Intro to Ruby

D3ce112caf8840c3c95b2ab307a36879?s=47 Nick McCurdy
September 18, 2014

A Quick Intro to Ruby

A tour of Ruby's basic syntax for novice programmers.

D3ce112caf8840c3c95b2ab307a36879?s=128

Nick McCurdy

September 18, 2014
Tweet

Transcript

  1. A Quick Intro to Ruby by Nicolas McCurdy

  2. What is Ruby? Ruby is a programming language that is…

    • dynamically typed • object oriented • flexible • inspired by many features of other languages
  3. Hello World puts “Hello, world!” Note that, similarly to Python,

    code doesn’t have to be in a class, method, or module. This makes Ruby very useful for scripting. Running from a file: ruby hello.rb
  4. Methods def double(number) number * 2 end # Note that

    parentheses for method calls are optional double 5 # 10 # This also works double(5)
  5. Methods with Optional Arguments def greet(name = “Ruby”) puts “Hello,

    I am #{name}.” end greet # Hello, I am Ruby. greet “Nick” # Hello, I am Nick.
  6. Simple Types Strings • “Hello” or ‘Hello’ • Mutable. Numerics

    • 4 or 4.0 • Note that Fixnums and Floats are two separate subclasses of Numerics. Booleans • true or false Symbols • :green • Immutable. • Useful for representing an arbitrary value (use this where you want an enum or a String that represents an arbitrary value but isn’t displayed).
  7. More Types Arrays • [“One”, 2, :3] • Arrays are

    dynamically typed, so they can contain values of different types. • Arrays are more like what other languages call “lists”, since they can be modified. Ranges • 0..10 • Can be used to into into an array like this: array[0..10] Hashes • person = { “Name” => “Bob”, “Age” => 15 } • Like a dictionary or hash map in other languages. • person = { name: “Bob”, age: 15 } • name: “Bob” is the same as :name => “Bob”, but easier to read and write. • Looking up a value: person[:name]
  8. Classes # Create the Person class class Person def initialize(name)

    @name = name end attr_reader :name def greet(other) puts “Hello #{other.name}, I am #{@name}.” end end # Create two people that will greet each other matz = Person.new(“Yukihiro Matsumoto”) david = Person.new(“David Heinemeier Hansson”) matz.greet(david) # output: Hello Yukihiro Matsumoto, I am David Heinemeier Hansson.
  9. Modules # Add to Ruby’s existing Math module module Math

    def self.double(number) number * 2 end end # Call the method directly off the module Math.double(5) # Output: 10
  10. Additional Resources • tryruby.org • ruby-lang.org/en/documentation/ • irb