Intro to Ruby

Class 3

Let's talk more about hashes

Remember hello_rubies.rb?

Let's update that with more details about YOU!

Copy and paste this to create ruby_far_class.rb

Review

  • Conditions - if, elsif, else
  • Loops - while
  • Arrays - [1,2,3]
  • Hashes - {"one" => 1, "two" => 2}

Homework Discussion

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

Check Out Homework Solutions:
Pet shop
Bye Grandma
Let's check out HW grandma.rb to review

            chatting = true
            byes = 0
            while chatting
              puts "Ask Grandma a question:"
              said = gets.chomp!
              if said == "BYE"
                byes += 1
                if byes > 2
                  chatting = false
                else
                  puts "** Grandma is ignoring you **"
                end
              elsif said == said.upcase
                year = 1930 + Random.rand(20)
                puts "NO, NOT SINCE #{year}!"
              else
                puts "HUH?!  SPEAK UP, SONNY!"
              end
            end
            puts "Thanks for chatting with Grandma"
            

What we will cover today

  • Methods
  • Objects
  • Object Oriented Programming

Note: you can download all the files from the class here. Click Clone or Download, then Download zip. Then, cd into day_3 so you can run the files we cover. You can also copy and paste into repl.it

Methods

A method is a name for a chunk of code

Methods are often used to define reusable behavior.


                        1.even?
                        => false

                        "fred".capitalize
                        => "Fred"
                        
                        "fred".class
                        => String

                        "stressed".reverse
                        => "desserts"
                        

If you have code you want to reuse or organize, methods will help.

Writing A Method

Just like with loops and conditionals there is a term used to declare a method, def and end


            def subtract(x, y)
              x - y
            end
            

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

Calling A Method

Arguments are passed
and parameters are declared.

Note that the variable names don't have to match!

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


              def subtract(x, y) # x, y are parameters
                x - y
              end

              subtract(5, 2) # 5, 2 are arguments
            

Returning Values

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. Let's run subtract.rb both ways (in Terminal load 'subtract.rb', ruby subtract.rb and repl.it)


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

            return_value = subtract_one(5, 2)
            puts return_value

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

            return_value = subtract(5, 2)
            puts return_value

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

            return_value = subtract_two(5, 2)
            puts return_value

              

Local Variables

A local variable is a variable whose scope ends (goes out of context) when the function returns
Let's run the broken doublethis.rb and then fix


      def doubleThis num
        numTimes2 = num*2
        puts num.to_s+' doubled is '+numTimes2.to_s
      end

      doubleThis 44
      puts numTimes2.to_s     
      

Let's Develop It!

Write a method takes in a String question and returns an answer.

Try it on your own first. If you're stuck, you can check out question.rb

Default Values

If using 1.9 or lower, these have to be the last arguments in your list.

Default values are used if the caller doesn't pass them explicitly.


            def eat(food = "chicken")
              puts "Yum, #{food}!"
            end

            >> eat
            Yum, chicken!

            >> eat "arugula"
            Yum, arugula!
              

Let's Develop It!

Lets write a method called englishNumber. It will take a number, like 22, and return the english version of it (in this case, the string 'twenty-two'). For now, let's have it only work on integers from 0 to 100.

Stuck? This file will get you started. See if you can fill out pieces that we need.
Still stuck? Here's a simplish (imperfect) solution
Solution (will be assigned as homework), but make sure you understand the previous two files first and give it your best shot before opening.

Objects

An Object is an instance of a Class

Objects do things and have properties.

Classes define a template for objects.

Classes describe what a certain type of object can do (methods) and what properties (attributes) they have.

Instantiation

We typically use .new to create an object


            my_array = Array.new
            

What happened here?

  • created an instance of Ruby's Array class
  • stored it in the variable my_array - we have an object!
  • my_array is an object or instance of class Array
  • creating a new object or instance from a class is called instantiation
  • we've instantiated an object called my_array from the class Array

Instance Variables

Expand scope

Names start with an @

Only visible inside the object


            class Cookie
              def add_chips(num_chips)
                @chips = num_chips
              end

              def yummy?
                @chips > 100
              end
            end

            cookie = Cookie.new

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

Object Oriented Programming (OOP)

  • Object Oriented Programming is one of many programming approaches: procedural, event-driven, functional, declarative...
  • OO languages: Java, C#, C++.
  • "In OOP, computer programs are designed by making them out of objects that interact with one another." -- wiki
  • You might choose OOP because Objects make things easier to understand and act as a natural way to modularize code. OOP can be easier to maintain and change.

OOP & Inheritance

Just as you inherited traits from your mom, your objects may inherit traits from other objects.

Inheritance is when you use one class as the basis for another.

You might use Inheritance if you have an existing class that you want to expand in different ways, depending on the object. Think: characters, vehicles, dogs!


                          class MyString < String
                          end

                          my_string = MyString.new
                          my_string.upcase
                        

Let's Develop It Together!

Lets build a class, GDIArray, that inherits from Array. Add a method to GDIArray that returns "nonsense"

Questions?

Homework

Use the ask method to enhance your text-based Adventure game.

Add more methods to your Adventure game!

Homework

Expand upon englishNumber. First, put in thousands. So it should return 'one thousand' instead of 'ten hundred' and 'ten thousand' instead of 'one hundred hundred'.

Expand upon englishNumber some more. Now put in millions, so you get 'one million' instead of 'one thousand thousand'.

Then try adding billions and trillions. How high can you go?

Intro to Programming in Ruby

@gdifar


We are done with class 3!

Setup   |   Class 1   |   Class 2   |   Class 3