Intro to Ruby

Class 4

Let's Develop It- Possible Solutions

$pets.length

$pets.first[:name]

$pets.each{|p| puts p[:name]}

$pets.select{|p| p[:nocturnal] == true}.count

$pets.select{|p| p[:legs] == 4}.each{|p| puts p[:name]}

Methods

A method is a name for a chunk of code

Methods are often used to define reusable behavior.

Let's look at methods we've already used:


1.even?
=> false

"fred".capitalize
=> "Fred"

puts "Hello there"
Hello there
=> nil
          

If you have some code you want to reuse or organize, methods are the way to do it.

Write a Method

Let's write a method together (in IRB)

def means define

subtract is the name of the method

x, y are parameters

x - y is the body of the method

x - y is also the return value


def subtract x, y
  x - y
end
        

Method Return Value

Every Ruby method returns something.

Usually, it's the last statement in the method.

It could be the value sent to return if that came first.


def subtract(x,y)
  x - y
  'another thing'
end

puts subtract(5, 2)

def subtract(x,y)
  return x - y
  'another thing'
end

puts subtract(5, 2)
          

Let's Develop It!

Let's write a method that takes in a number and tells us if it is even.

It could return string, like "even" or "odd", or a boolean, like true or false.


def method_name(parameter)
  # method implementation
end
          

Hint: if number % 2 == 0, then it is even

Arguments vs. Parameters

Technically speaking, arguments are passed and parameters are declared.

In this code, 5 is an argument and x is a parameter

In reality, you'll often hear the terms used interchangeably


def subtract(x,y)
  x - y
end

subtract(5, 2)
          

Parentheses

The parentheses around arguments and paramaters are optional in Ruby.

I find that using them makes your code clearer, and recommend it.


# They're often ommitted for the puts method

puts "HELLO"

puts("HELLO")
          

Methods & Variables

Local variables are only available in the methods where they were defined.


# Let's assign the length of the parameter to a local variable
def length_finder(our_string)
  length = our_string.length
end

puts length
  => NameError! :(
          

Objects

An Object is the building block of a program.

Objects do things and have properties.

Object: Number
What can it do?
- Add
- Subtract
- Divide
- Multiply

What are some properties of your Number?
- Length
- Base
- Even
          

Object Class

Objects can be grouped by Class.

Classes define a template for objects. They describe what a certain type of object can do and what properties they have in common.

There are many kinds of objects, including String, Number, Array, Hash, Time, ...

To create an object we use .new


new_arr = []
new_arr = Array.new
          

now new_arr refers to an object instance

Instance Variables

Represent object state

Names start with an @

Only visible inside the object


cookie = Object.new

def cookie.add_chips(num_chips)
  @chips = num_chips
end

def cookie.yummy?
  @chips > 100
end

cookie.add_chips(500)
cookie.yummy?   #=> true
          

Object Oriented Programming

  • Object Oriented Programming is one of many programming approaches: procedural, event-driven, functional, declarative...
  • These days, most programming is done in an OO language: Java, C#, C++.
  • All this means is that programs are organized around objects (data & methods).
  • You might choose OOP because Objects make things easier to understand and act as a natural way to modularize code. When a large code base is composed of many small Objects, it is easier to maintain and change.

Built in classes of Ruby

Ruby has many classes predefined:

  • String
  • Integer
  • Float
  • Array
  • Hash

They are commonly used object types, and have methods associated with them already. How convenient!


a = Array.new
b = String.new
          

Built in classes of Ruby

When we create new objects from these classes, we can do things with them immediately.

To see all methods associated with an object or class, run ".methods" on it.


b = "holy cow!"
b.methods
          

You can view all the built in classes and their associated methods in the Ruby documentation.

Creating a Class

It's very easy to create your own classes in Ruby.


# die.rb
class Die

  def roll
    @numberShowing = 1 + rand(6)
    #rand(6) returns a random-ish number between 0-5
  end

  def showing
    return @numberShowing
  end

end
          

Inside the class, define its methods.

Creating a Class

You can use your class right away by loading it into IRB.


#in irb
load 'die.rb'
die = Die.new
die.roll
puts die.showing
        

You can use it in another file by requiring it. We'll discuss this later.

Refactoring a Class

What is the result of calling the .showing method on a newly-created, un-rolled Die object?

We can avoid this by calling the roll method as part of the creation of a new instance of Die.


# die.rb
class Die

  def initialize
    roll
  end

  def roll
    @numberShowing = 1 + rand(6)
  end

  def showing
    @numberShowing
  end

end
          

Let's Develop It

  • In your text editor, create a Character class with an initialize method that sets inital values, and at least one other method.
  • Open IRB and load the class. Create one or more objects from the class and run some methods on them.
  • You could use the next slides as an example.

Example of creating a class


# in character.rb
class Character
  def initialize(name)
    @name = name
    @health = 10
  end

  def heal
    @health += 6
  end

  def adventure
    if @health > 0
      puts "The dragon hugged #{@name} kind of hard..."
      @health = @health - 5
    else
      puts "#{@name} is dead :("
      exit
    end
  end
end
          

Running example program in IRB


# in irb
load 'character.rb'
me = Character.new("Cheri")
me.adventure
me.heal
me.adventure
# repeat until you're done having fun

          

Inheritance

Classes can inherit from one other class.

All elves are characters, so if all characters have an adventure method, so do all elves. Elves may also have their own methods that other characters do not.

Inheritance

Denote that Elf inherits from Character by using the < symbol


# in character.rb, after Character class code
class Elf < Character
  def twinkle
    puts "I'm super magical!"
  end
end

#in irb
load 'character.rb'
me = Elf.new("Cheri")
me.adventure
me.twinkle
          

Notice that the initialize method was also inherited, as our new Elf knows its name and started off with 10 health.

Inheritance

Subclasses may differ from from their super classes in some ways. Methods can be overwritten when this is the case.


# in character.rb, after Character class code
class Elf < Character
  def twinkle
    puts "I'm super magical!"
  end

  def heal
    @health += 8 # it's easier to heal when you're magic
  end
end

#in irb
load 'character.rb'
me = Elf.new("Cheri")
me.heal
          

More information about inheritance can be found here.

Putting it all together

For a command line program, you need these pieces:

  1. File(s) containing your class definitions
  2. A file containing your program, which requires the class file(s)
  3. To call the program file from the command line (not IRB)

Putting it all together

The file containing your class definitions, here called character.rb:


# in character.rb
class Character
  # contents of class here
end

class Elf < Character
  # contents of class here
end
            

Putting it all together

The file containing your program, here called adventure.rb, which requires the class file:


# in adventure.rb
require_relative 'character.rb'
#file path relative to the location of adventure.rb file
require_relative 'die.rb'


puts "Your name?"
char = Character.new(gets.chomp)
# plus lots more adventuring.....
            

Putting it all together

Call the program file from the command line:


#in command line
ruby adventure.rb
# then have some fun!
            

Let's Develop It

Putting it all together: A role-playing game!

  • Build more methods for the Character class, and some subclasses of Character (Orc? WarriorPrincess?).
  • Write a command-line program that calls your Character and Die classes to allow the user to have an adventure!
  • Maybe user can choose their character type?
  • Maybe the user's progress will be dependent on outcome of dice-rolling?

Questions?

Further Resources

Ruby-doc.org Official Ruby Documentation
Project Euler Offers tons of small math problems to be solved via programming, plus forums to share and discuss solutions
Ruby Monk Free, interactive, in-browser tutorials
Ruby the Hard Way Fun, free (HTML version) book with great information about programming
Sinatra A basic web app framework that runs on Ruby
The Rails Tutorial The Rails web app framework is the most popular use of Ruby... are you ready to dive in?
Girl Develop It Local workshops, events, and coding sessions with awesome people

Homework

Practice: Make your final project even bigger and better! If you're taking this class as part of a job plan, attend a local meetup and talk to a couple of strangers about what you've learned and what you're excited about doing with programming.