GDI Logo Badge

Intro to Ruby

Class 4

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • We are here for you!
  • Every question is important.
  • Help each other.
  • Have fun!

Homework Discussion

How was last week's homework? Do you have any questions or concepts that you'd like to discuss?

HW: English Numbers

You could expand the EnglishNumbers program by adding the following code to deal with thousands:


left  = number  #original code, set 'left' variable

write = left/1000          #  How many thousands left to write out?
left  = left - write*1000  #  Subtract off those thousands.

if write > 0
  thousands  = englishNumber write
  numString = numString + thousands + ' thousand'

  if left > 0
    numString = numString + ' '
  end
end

write = left/100 # this line begins the code that deals with hundreds
                  

HW: Wedding Numbers

You could modify the code in the EnglishNumbers program to make it WeddingNumbers by replacing some of the added spaces with added 'and's and spaces:


# numString = numString + ' '   # old code

numString = numString + ' and '
                   

HW: 99 Bottles of Beer

You could modify the code for 99 Bottles of Beer shown in Class2 to include the functionality in the EnglishNumber class:


require_relative 'englishnumber.rb' 
num_bottles = 999

while num_bottles > 0
  puts "#{englishNumber(num_bottles)} bottles of beer on the wall, 
  #{englishNumber(num_bottles)} bottles of beer, take one down, pass it 
  around, #{englishNumber(num_bottles - 1)} bottles of beer on the wall!"

  num_bottles = num_bottles - 1
end 
                   

Review

  • What is a method?
  • Creating & calling a method
  • What is an object?

What would you like to see reviewed?

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.

Extending a Class

You can write new methods for the built in classes of Ruby. They will then be available to all instances of that class in your program.


class String
  def get_excited
    return self + "!!!" 
  end 
end 
                    

"self" refers to the object calling the method.

You can redefine existing methods for classes this way, too, but it's not recommended.

Creating a Class

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


Make a file called die.rb


# 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.


Remember to start IRB in the same directory as your file.


#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.

Improving a Class

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


# 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 
                    

Improving a Class

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


# die.rb
class Die
  
  # new initialize method
  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 "Animal" class with an initialize method that sets the Animal's name, 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 code


# in animal.rb
class Animal 

  def initialize(name)
    @name = name
    @color = "blue"
  end

  def change_color
    @color = "red"
  end 

  def romp
    if @color == "red"
      puts "#{@name} loves running around and playing"
      puts "#{@name} is getting tired..."
      @color = "blue"
    else 
      puts "#{@name} is too sad or tired to romp right now :("
      exit
    end
  end
end
                    

Running example program in IRB


# in irb
load 'animal.rb'
mittens = Animal.new("Mittens")
mittens.romp
mittens.change_color
mittens.romp
# repeat until you're done having fun

                    

Inheritance

Classes can inherit from one other class.

All cats are animals, so if all animals have an romp method, so do all cats. cats may also have their own methods that other animals do not.

Inheritance

Denote that Cat inherits from animal by using the < symbol


# in animal.rb, after animal class code
class Cat < Animal
  def speak
    puts "Meow!"
  end 
end

#in irb
load 'animal.rb'
mittens = Cat.new("Mittens")
mittens.romp
mittens.change_color
                    

Notice that the initialize method was also inherited, as our new Cat knows its name and started off with red color.

Inheritance

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


# in animal.rb, after animal class code
class Cat < Animal
  def speak
    puts "Meow!"
  end

  def change_color
    @color = "purple" # nothing cats do makes any sense
  end 
end

#in irb
load 'animal.rb'
mittens = Cat.new("Mittens")
mittens.change_color
                    

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 animal.rb:


# animal.rb

class Animal
  # contents of class here 
end

class Cat < Animal
  # contents of class here 
end
                    

Putting it all together

The file containing your program, here called digital_pet_game.rb, which will run from the command line and requires the class file:


# digital_pet_game.rb

require_relative 'animal.rb' 
  #file path relative to the location of digital_pet_game.rb file
require_relative 'die.rb'


puts "Your name?"
char = Animal.new(gets.chomp)
                    

Putting it all together

Call the program file from the command line:


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

Let's Develop It

Putting it all together: A digital pet game!

  • If you didn't write a Animal class, copy and paste the code to get one started.
  • Create a few subclasses of Animal.
  • Write a command-line program that calls your Animal subclasses to allow the user to have a digital pet!
  • Maybe user can choose their Animal type?

Bonus: Let's Develop It

Putting it all together: A digital pet game!

  • Maybe the user's animal's behavior will be dependent on outcome of dice-rolling?

Survey time!

link to survey

Questions?

Further Resources

  • Ruby-doc.org - Official Ruby Documentation
  • Ruby Monk - Free, interactive, in-browser tutorials
  • Ruby the Hard Way - Fun, free (HTML version) book with great information about programming
  • JumpstartLab Tutorials - Lots of small projects to practice Object Oriented thinking and builds you up piece by piece into building apps with Ruby on Rails
  • 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
  • Rails Girls Atlanta - Monthly meetup for women learning Ruby on Rails
  • Atlanta Ruby User's Group - Several monthyly meetups dedicated to hacking and presentations

Homework

Challenge yourself: Make your final project even bigger and better! If you're taking this class as part of a job plan, attend a Atlanta Ruby Users Group (ATLRUG) meetup and talk to a couple of strangers about what you've learned and what you're excited about doing with programming.


Practice: Try some of the tutorials in the further resources list. Review the command line tutorial from week 1 and keep learning new commands.

Make friends: Attend future GDI Atlanta Code & Coffee events and classes, Rails Girls Atlanta meetups, and any other local events that interest you!