Intro to Programming with Ruby

Class 1

About Us

Amanda Muñoz

Software Engineer, Wellist

Sean Kelly

Introduce Yourself!

  • Who are you?
  • What is your programming experience
  • What do you hope to get out of this class?
  • What is your favorite food?

What we will cover today

  • Installation and tools
  • Command Line Basics
  • What is programming?
  • Why Ruby?
  • Variables, Arithmetic & Objects

Installation

Click here to access Railsbridge's Installfest instructions to get set up.

  • Work through the instructions for your operating system.
  • STOP after the "Configure Git" step.
  • This process should take about an hour.

Railsbridge is an organization that holds a day long Ruby on Rails workshop several times a year. You should check them out! They are a national organization with a Boston chapter.

Command Line Basics

Using the command line and working in the terminal can be really intimidating at first!

With practice, navigation and file manipulation is significantly faster in the terminal than in the GUI (graphical user interface).

Professional software developers use the terminal all the time,
and this class will require some use of it.

(plus, you get to feel like a stealthy hacker)

Command Line Basics

Mac & Linux users: Open Terminal

Windows users: Install & Open Git-Bash


We will not be using Windows "cmd" program,
as it uses a different syntax than *NIX systems.

Intro to Terminal Prompt

The line that appears in the terminal when you open it is called
the prompt.

It usually contains information about the user and current directory.
It can be customized.

example prompt example prompt example prompt example prompt example prompt

Terminal instructions often start a line with a $.
This just represents the last character in the prompt in the bash shell, you don't have to type it.

Command Line Cheatsheet

. the current directory- ex: touch ./wow.txt
.. the parent of current directory - ex: cd ../RubyParty
~ the root directory- ex: cd ~/Pictures
cd [location] "change directory" to [location]
pwd "present working directory" - where am I?
ls -al "list all" of the contents of current directory, including invisible ones
touch [filename.extension] create a file called [filename.extension] in the current directory
mkdir [directoryname] create a directory called [directoryname] in the current directory
With great power comes great responsibility. Be very careful with this one.
rm [filename] "remove" (delete) the file called [filename]
rm -rf [directoryname] "remove recursively with force" the directory called [directoryname]
clear OR cmd+k clear the terminal screen
help lists all possible commands
man [command] displays the manual for [command]

Command Line Activities

Homework!

You're all set up!

What is programming?

  • Ada, Countess of Lovelace.
  • Charles Babbage's Analytical Engine
  • A program is made of one or more files of code, each of which solve part of the overall task.
  • Code is human readable.
  • But the computer needs specific instructions to run that are not as easy to read.

What is programming?

  • Teaching the computer to do a task.
  • To create the form of code the computer can use, we use the Ruby interpreter. Other languages use other interpreters or a compiler
  • Don't focus on what's "under the hood" for now. We will "drive the car" first.

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 calculator functions


                3 + 4

                2 * 4

                6 - 2

                4 / 2

                4 /* 2
                => SyntaxError: (irb):10:syntax error, unexpected *
              

Arithmetic

Other Ruby Math Operators


                11 % 5
                => 1

                2 ** 3
                => 8

              

Errors are Neat!

  • 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 are references to information.
  • We reference variables by name.
  • 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
            

Ruby's Variables and Constants

  • Ruby has variables, constants and literals.
  • A variables starts with a lower case letter or an underscore character (_) and consists entirely of letters, numbers and underscores.
  • Constants do not change and are typically in all caps.
  • Literals are literal values, for example the number 3 or the string 'hi'

            # variables
            age = 50
            _age = 50
            _my_age = 50

            # constants
            PI = 3.14159

            # literals
            3
            'hi'
            

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"
            

Local Variable Values

  • No default value
  • No type declaration
  • Do not live forever

            # error
            name

            # defined, initalize, create
            name = "KC"
            defined?(name)
            

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
  • Let's explore a few built in Objects

            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.


              irb> 1_000_000_000_000_000_000.class
               => Fixnum
              irb> 1_000_000_000_000_000_000_000.class
               => Bignum
            

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


              irb> 1.001.class
               => Float
            

Number Practice


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

How many seconds are in an hour?

How many minutes are in a week?

How many years old are you if you've been alive 1 million seconds?

Strings

Strings are characters inside double or single quotes.


            a = 'Hello '
            b = "World"
            c = a + b
            c.reverse
            => "dlroW olleH"
            

            a = "Spam "

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

String Practice


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

What is the reverse of your name?

How many characters long is your name?

Can you repeat the word hello 100 times?

What is the 5th character of my name?

Methods

  • Methods define the behavior for an Object.
  • The "." is an operator that connects the Object of the method to the method.
  • String Objects can reverse, for example.
  • Let's call some 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
              

User Input

  • To obtain user input, use gets
  • To print out information, use puts
  • Let's create our first program together

Put the code below in a file and save it as name.rb


                        puts 'Hello there, and what\'s your name?'
                        name = gets
                        puts 'Your name is ' + name.chomp! + '? What a lovely name!'
                        puts 'Pleased to meet you, ' + name + '. :)'
                        

Run your program from the command line:


                          ruby name.rb
                        

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!

Intro to Programming in Ruby

@gdiBoston  


Thats all, folks!

This is a lot of info, please ask lots of questions!

Send us emails if you don't want to ask here!

amadag.munoz@gmail.com | smattkellygmail.com

Setup   |   Class 1   |   Class 2   |   Class 3   |   Class 4