Intro to Ruby

Variables, Arithmetic, Methods, Objects, Errors

Install Discussion

How was the install and playing with command line? Do you have any questions or concepts that you'd like to discuss?

Why Ruby?

  • It reads like English. The syntax is intuitive.
    
                        # Java
                        for(int i = 0; i < 5; i++)
    
                        # Ruby
                        5.times do
                      
  • The community is large, active and interested in helping others learn.
  • You can get a web app off the ground quickly.

What is Ruby used for?

Who is using Ruby?

Working with Interactive Ruby Shell (IRB)

  • IRB is a command line interface to Ruby that is installed along with Ruby. It works kind of like a calculator and is a great way to get started quickly.
  • Open: In the terminal, type irb
  • Quit: Type quit and then press enter
  • Follow along with the examples in the slides ahead. Type them in!
  • Feel free to explore as well. You will not accidentally break things.

Arithmetic

Try out some operators


                  3 + 4

                  2 * 4

                  6 - 2

                  4 / 2

                  11 % 5

                  2 ** 3
                

Errors are da best!

  • There are different kinds of errors that can occur. We just saw the SyntaxError which often helps us find misspelled words or missing quotes.
  • Take time to read each Error. They often tell you how to fix the issue and can be a great starting point when searching for help online.

              irb> hi
              NameError: undefined local variable or method 'hi' for main:Object
                
`

Variables

  • Variables label and store information.
  • They are called variables because the
    information they reference may change.

              # Everything after this pound sign will not be evaluated.
              # These are called comments and I will use them to annotate code
              age = 50
              days_in_year = 365
              days_alive = age * days_in_year
              => 18250
            

What can I do with a variable?

  • Create - Initialize - Define
  • Access - Read
  • Assign - Replace

            # create and assign in one line
            age = 0

            # access the value in age
            age

            # replace value in age
            age = 40
            

Variable naming

  • Make it meaningful
  • Make it easy to read
  • Make it concise
  • Should be unique
  • Should be understood by someone who has no idea what your program does

            # good
            occupation = "software developer"

            # bad
            occupation_i_always_dreamed_of_having_in_seattle = "software developer"
            o = "software developer"
            1st_occupation = "software developer"
            

Methods

  • A method in Ruby is a set of expressions that returns a value. Other languages sometimes refer to this as a function.
  • Ruby has many built in methods. We can also create our own methods.
  • The "." is an operator that connects the Object of the method to the method.
  • "If objects (like strings, integers, and floats) are the nouns in the Ruby language, then methods are like the verbs." from Learn to Program

Example methods


              irb> puts "hello"
              hello
              => nil

              irb> "2".to_i
              => 2

              irb> 2.to_s
              => "2"

              irb> "2" / 5
              NoMethodError: undefined method '/' for "2":String
            

We'll practice building our own methods on Wednesday!

Data Types

Numbers   |   Strings   |   Symbols   |   Booleans
Regular Expressions   |   Arrays   |   Ranges   |   Hashes

  • Data always has a "type"
  • You will hear the words Class/Type/Object used interchangeably

            irb> 1.class
            => Fixnum

            irb> "Hello".class
            => String

            irb> 1.0022.class
            => Float

            irb> [1,2,3].class
            => Array
            

Numbers

Numeric data comes in two types: Integers and Floats

Integers are either Fixnum or Bignum. They do not have decimals.

Note: underscore characters are ignored in the digit string.


              irb> 100000000000000000.class
               => Fixnum
              irb> 1_000_000_000_000_000_000.class
               => Fixnum
              irb> 1_000_000_000_000_000_000_000.class
               => Bignum
               irb> 1,000,000,000,000.class
              => SyntaxError: (irb):3: syntax error, unexpected ',', expecting end-of-input
              1,000,000,000,000.class
                ^ 
            

Floats have at least one number to the left of a decimal point.


              irb> 1.001.class
               => Float
            

Number and Method Practice


            7/8
            7.to_f/8
            7.0/8.0
            3.14.to_s
            3.14.to_i
            "2" * 5
            1 + "2"
            1 + "2".to_i
            (1 + 2) * 3
            1 + (2 * 3)
            

Strings

Strings are characters inside double or single quotes.


            a = 'Hello '
            b = "World"
            c = a + b
            c.reverse
            

            a = "Spam "

            # Here multiplying a by 4 concatenates (links) four strings together
            b = a * 4
            =>"Spam Spam Spam Spam "
            

String and Method Practice


            "Heather".upcase
            "Heather".downcase
            "heather".capitalize
            "Hello".reverse
            "Heather".length
            "Heather Moore".swapcase
            "".empty?
            

User Input

  • To obtain user input, use gets
  • To print out information, use puts
  • Let's create our first program together.
  • Type touch name.rb in Terminal.

This program should:

  • Request the user's name
  • Print out a greeting to user that includes their name

Let's Develop It

  • Write your own program using puts and gets to ask a user for their age and then tell them how old they are in dog years.
  • reminder: gets method returns a string. To do math on it, convert it to an integer with the .to_i method.
  • 
                  #1 dog year = 7 human years
                  user_age = gets.to_i
                  

Bonus Feature 1

Update your code to return a message in all capital letters.


            # YOU ARE 5 YEARS OLD IN DOG YEARS
            

Bonus Feature 2

Update your code to return a message in all capital letters, reversed with a count of the characters returned in parens.


            # YOU ARE 5 YEARS OLD IN DOG YEARS (32 characters)
            

Questions?

Homework

Practice: Write a command line program that asks the user for the year they were born, then calculates their age in years, days, and seconds. Tell the user how old they are in these different formats. (Note: you'll be using gets and puts in this program, along with some math)

Temperature conversion! Make a program that asks the user for the temperature in Fahrenheit and print out the temperature in Celsius and Kelvins.

More info: Read more on methods and some basic methods already given to you Chapter 5 of Learn to Program

Intro to Programming in Ruby

@gdifar


We are done with class 1!

We have done a lot, ask questions!

Part 1: Intros and Setup
Part 2: Ruby Party! Variables, Arithmetic, Methods, Objects, Errors