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.

Reminder! 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 existing 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, etc.

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

We now know how to create instances of these Classes:


    array = Array.new
    string = 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.


  new_string = "holy cow!"
  new_string.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

We can also create our own classes in Ruby that have their own methods!


  # die.rb
  class Die
    def roll 
      @number_showing = rand(1..6) 
    end 

    def showing 
      return "You rolled a #{@number_showing}!"
    end 
  end
                    

Creating a Class

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

In your terminal, navigate to the folder/directory where you saved your file and enter IRB from there.


  #in irb
  load 'die.rb'
  die = Die.new
  die.roll
  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.


  class Die
    def initialize 
      roll
    end 

    def roll 
       @number_showing = rand(1..6)
    end 

    def showing 
      return "You rolled a #{@number_showing}!"
    end 
  end 
                    

Let's Develop It

  • In your text editor, create a "Character" class with an initialize method that sets the Character'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 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 "#{@name} goes on a great adventure and meets a dragon!"
        puts "The dragon hugged #{@name} kind of hard..."
        @health -= 5
      else 
        puts "#{@name} is dead :("
        exit
      end 
    end 
  end
                    

Running example program in IRB


  # We can load our file in irb
  load 'character.rb'
  me = Character.new("Jess")
  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

We denote that our Elf Class inherits from our base Character Class by using the < symbol


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

  # load our file in irb
  load 'character.rb'
  me = Elf.new("Jess")
  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 (Elf) may differ from from their super classes (Character) 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

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

More information about inheritance can be found here.

Putting it all together

For a command line program that asks for user input and lets them play your adventure game, you need these pieces:

  • File(s) with your code that defines your character classes
  • A file containing your program, which requires the character class file(s)
  • To call the program file from the command line (not IRB), like we did in Class 2 with our adventure.rb file

Putting it all together

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


  # 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 will run from the command line and requires the class file:


  # adventure.rb

  # file path relative to the location of adventure.rb file
  # it is best to save these in the same directory/folder
  require_relative 'character.rb' 
  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:


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

Let's Develop It

Putting it all together: A role-playing game!

  • If you didn't write a Character class, copy and paste the code from the slides to get one started.
  • Create a few subclasses of Character.
  • 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?

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
Sinatra A small 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
Seattle.rb Ruby meetup group welcome to all skill levels. They are very newbie-friendly!