Ruby Basics – As much Ruby as Liz can teach you in 100 minutes.



Ruby Basics – As much Ruby as Liz can teach you in 100 minutes.

0 1


ruby_basics

A very beginner-level introduction to Ruby.

On Github feministy / ruby_basics

Ruby Basics

As much Ruby as Liz can teach you in 100 minutes.

 

Be my friend: liza@girldevelopit.com

Um, who are you?

I am a very nice person who loves:

  • tacos
  • teaching people how to code
  • gesturing a lot with her hands
  • dancing in public

     

    Sorry about those last two things.

Workshop Info

puts 'hello, beginners'

What to expect:

  • beginner level workshop for people who have never done programming
  • assumes you know nothing
  • if you know stuff, you will probably be bored and can totally leave now without feeling mean
  • requires you to use terminal and a text editor (download sublime text 2 if you haven’t yet)
  • you cannot use text edit
  • no, really, you cannot use text edit

Code Conventions

Text Editor or Terminal?

Text Editor: Displays your code with pretty syntax highlighting and lets you save.

# taco.rb
taco = "yummy"
puts taco
# => "yummy"

 

Terminal: Lets you run your code or play around in irb.

$ ruby taco.rb
# => "yummy"
The most important thing to distinguish here is that anything you type into the terminal is preceded by a $. You don't actually type the $ sign, just type everything after it. More on irb in a minute.

Exericses!

  • Some slides have bullets on them.
    • These bullets tell you what to do.
    • You should listen to the bullets...
    • or you won't learn anything.
  • Who run the world?
    • Girls. Beyoncé. Me. Bullets!

Two ways to run Ruby

there are two ways to run your ruby code. if you want to visually see the output, you use "puts". this prints whatever your result is to the terminal screen. puts works for both options here.

irb. in a file that you run as a program.

One: irb

Terminal:

$ irb
$ puts 'hello world'
# => 'hello world'
$ exit

this is an interactive ruby shell. open terminal and type irb (all lowercase, no spaces). this will drop you into an environment that has your version of ruby loaded. you can type ruby directly into irb. to leave irb, type ‘exit’ (all lowercase, no spaces). you have to type exit when you’re done or your computer will explode and instructure will be sad.

irb is really convenient and easy to use, but it won't save your code anywhere. for the bulk of this workshop, you won't be using irb unless specifically mentioned.

Two: in a file

hello.rb:

puts 'hello taco'

Terminal:

$ cd Desktop
$ ruby hello.rb
# => 'hello taco'

this is how we're going to be doing most of our ruby-ing today.

go into your text editor (Sublime Text) and make a new file. save it on your desktop and call it "hello.rb". type the lines on the slide and save. go to terminal and navigate to your file, then type 'ruby hello.rb' exactly as it appears and hit enter. you should see 'hello taco' print out in terminal.

Ruby time!

Variables

What is a variable?

a = 1

a is your variable

1 is the value of that variable

you can assign a value to a variable. you can assign any value you want to a variable, in this example the variable is ‘a’ and the value is ‘1’. that means anywhere in your code where you type ‘a’, its value will be inserted when your program gets run.

variables can be assigned to anything; we’re using a number here because it’s easy.

if you say this out loud, you would say "a equals 1", or "a is 1." ruby is often compared to plain english because it is very easy to read. plain english is also used when you’re naming variables in a real program, like canvas.

Variable naming rules

  • snake case (taco_party)
  • all lowercase
  • starts with a letter
  • no special characters except for _

ruby, like any good language, has a style guide that can provide you with more information about valid variable names.

Variable names

Yes!

  • hello_taco
  • taco5000

 

No! ABSOLUTELY NOT.

  • 99bottles
  • 34232
  • extra-chz
  • taco's?!

 

Special cases

  • TACO
  • Party

Yes!

  • underscores are ok, but they can’t be the first character. this is called snake case, you can use it to string words together
  • variables can contain numbers, but they can’t be the first character.

No!

  • you can’t start a variable name with a number. it will explode.
  • you can use a number as a variable. it will explode.
  • you can’t use a hyphen. it will explode.
  • guess what? quotations? also explode. that goes for any special character.

Wat?

  • all caps variable names are stylistically special. they’re called constants. there is nothing in ruby that says all constants have to be uppercase, or all uppercase variables have to be constants. until you know what a constant is, don’t use all uppercase variables.
  • capitalizing the first letter is also a special style thing in ruby. it is generally reserved for classes or modules and rubyists will get mad at you if you use them incorrectly.
  • rubyists like their style guide. it makes them feel organized and cohesive, kind of like a gang. it’s generally best to not violate the ‘suggested’ or ‘best practices’ rules.

Reserved words

there are some reserved words in ruby that you can’t use either. things like if, else, end, def, class, module, etc can’t be used as variable names because they have a special function in ruby. for now, just use fun variable names. it makes programming more exciting.

Numbers

Ruby can math!

hello.rb:

a = 1
b = 2
c = a + b
puts a + b
puts c

Terminal:

$ ruby hello.rb
# => 3
# => 3

open up your hello.rb file with your text editor. we’re going to stick with numbers for now. type out something similar to what i have above - don’t be afraid to change the numbers!

variables are how you save a tiny piece of information to use again, or to use later.

we’re assigning 3 variables here: a, b, and c. a and b are assigned to numbers; c is assigned to the total of those two variables. ruby is smart enough to know that a and b are numbers, and c should be the total of those two numbers.

Exercise: Math in irb

  • Open up irb
  • Type this into it:
a = 5
b = 10
c = 2
d = c * a - b

 

What is d?

0

Exercise: Such math

  • Assign some numbers to variables and do some math.
  • Write code in irb or save your file and run with terminal.
    • What happens when you combine operators?
    • What happens when you use decimals?
    • Do you get any unexpected results? *

 

* try and blow it up :)

Modulo

Can you guess what modulo does?

hello.rb:

puts 10 % 5
puts 10 % 3

Terminal:

$ ruby hello.rb
# => 0
# => 1
this returns the remainder if the first number is divided by the second.

Strings

Strings

hello.rb:

first_name = 'Liz'
last_name = 'Abinante'

name = first_name + ' ' + last_name
name_alt = "#{first_name} 'The Taco' #{last_name}"

puts name
puts name_alt

Terminal:

$ ruby hello.rb
# => Liz Abinante
# => Liz 'The Taco' Abinante

strings can be assigned to variables, too. strings can also be added together.

note the two different methods!

the first is concatenation, the second is interpolation. you can use either one.

Strings: with numbers!

hello.rb:

age = '28'
name = 'Liz Abinante'

puts name + ' is ' + age

Terminal:

$ ruby hello.rb
# => Liz Abinante is 28
strings can contain numbers, but you can’t do math with the string-ified number. it will treat it like a string, not a number.

Exericse: Very variable

  • Create the following variables and assign them values:
    age
    name
    city
    favorite_color
    favorite_food
  • Use concatenation or interpolation to create new variables.
  • What do you expect? What do you get?
  • What happens when you do this?
    puts name * 15

Playing with strings

Nicely (sometimes)...

!

Objects in Ruby are mutable.

Lots of String class methods have destructive and non-destructive counterparts.

Objects in Ruby are mutable. What this means is they can be changed in a destructive manner - if you apply a change to your object that is destructive, it will never be the same again. There is no undo button, no history.

How do you know if you're being destructive or not? Many destructive methods have a bang character - or exclamation point - at the end of them to signal to you to proceed with caution.

non-destructive methods return a copy of your string with the change applied to it

destructive methods are going to return your string with the change applied to it

.delete and .delete!

Add code to hello.rb and then run it in Terminal.

me = "Liz"
me.delete("z")
puts me #=> "Liz"

me.delete!("z")
puts me #=> "Li"
From this point foward, we're going to be add the code into our hello.rb file (or another file if you want) and then running it in Terminal. I won't be showing the input and output side by side like previous slides. The output is going to be shown in-line from here on out.

.swapcase and .swapcase!

me = "Liz"
me.swapcase!
puts me #=> "lIZ"

.reverse and .reverse!

party = "all the time"
party.reverse!
puts party # => "emit eht lla"

<<

letters = "abc"
letters << "domino"
puts letters
# => "abcdomino"
Very important to note that this is destructive

Arrays

Arrays

things_in_tacos = ["cheese", "guacamole"]
things_in_salsa = ["lime juice", "mangos"]

things_in_my_belly = [things_in_salsa, things_in_tacos, "ice cream"]

arrays are collections. they’re an ordered group of other objects. you can insert all sorts of things into arrays: you’re not limited to strings or numbers, you can add other arrays (mind blown) and fancy ruby objects. things in your array will stay in the order you put them unless you tell them to move around.

an array is distinguished in code by brackets: []

.length

array = ["chickens", "two cents", "ke$ha"]

array.length
# => 3

you can count the number of things in your array with array.length

Using the index

array = ["chickens", "two cents", "ke$ha"]

array[0] # => "chickens"
array[1] # => "two cents"
array[2] # => "ke$ha"

 

What happens if you try array[432]?

# => nil

because arrays are an ordered list of items, every item has a position. this position is called an index. you can find the item in an index by using the bracketed syntax pictured above and typing an integer.

note that arrays start counting at index 0.

Adding new items

taco = ["cheese", "guacamole"]
taco << "sour cream"
taco << "potato chips" << "jelly beans"
# => ["cheese", "guacamole", "sour cream", "potato chips", "jelly beans"]

 

WAT. Isn't << for strings?!?! How?

Duck typing!

remember when we played with strings and we saw the << syntax? how does ruby know that we’re not trying to add a string together here?

ruby is what is called a duck typed language. if you’re me, you’ll spend your whole life trying to remember what duck typed is short for, but what you really need to know is that ruby doesn’t require you to state what kind of object something is. ruby knows. ruby knows to use the push method for an array and not a string. it’s magic.

Playing with arrays

Nicely (sometimes)...

Playing with arrays: two ways

Changes the array itself, not the individual items in it.

sundae = ["ice cream", "hot fudge", "peanuts"]
sundae.reverse!
sundae # => ["peanuts", "hot fudge", "ice cream"]
alphabet = ["x", "l", "a", "b", "d", "c"]
alphabet.sort # => ["a", "b", "c", "d", "l", "x"]
alphabet # => ["x", "l", "a", "b", "d", "c"]

 

Changes each item in the array

Iteration

Array class methods: These are things like sort, reverse, shuffle, etc. They don't do anything to the individual objects inside of the array. They: change the order of items, select random items, remove specific items, etc. Just like the string class methods, these can be destructive or non-destructive. They don't always contain a bang character, so it's really good to read the documentation if you're trying something new.

Iteration

favorite_foods = ["cheese", "chocolate", "tacos", "ice cream"]
favorite_foods.each do |food|
  puts "I like to eat, eat, eat, #{food}."
end
# => "I like to eat, eat, eat, cheese."
# => "I like to eat, eat, eat, chocolate."
# => "I like to eat, eat, eat, tacos."
# => "I like to eat, eat, eat, ice cream."

Sometimes a difficult concept to grasp, iteration is very cool and awesomely powerful.

At the core of iterating over arrays is the 'each' method. They allows you to access EACH item in the array. What you do with the item at that point is up to you.

Exercises: Using each...

  • Print all of the items in your array as uppercase words
  • Print the index of each item in your array
  • Print all of the items in your array reversed, and reverse the order of your array

Link to the Array class docs is available in Canvas.

each is justt an example of iterating over each item in arrays. You can use other methods that will go down deep and do other magical things to your arrays. These are call enumerables. They're a little beyond the scope that we have time to cover, but if you keep practicing Ruby, they are a core component of the language.

Conditionals

if

Conditionals change how your code responds.

num = 88

if num % 2 == 0
  puts "This is an even number. YAY!"
end

# => "This is an even number. YAY!"

Conditionals can be very simple, or very complex. There are a few different types of conditionals in Ruby, the most basic is if.

If the statement following 'if' is truthy (true or a value that is true), then the code in that block will execute. If it's not true, it will continue to skip through your conditional until it finds something that applies to it. In this case, your number is even, so it will print this statement out to your terminal.

What would happen if num was 31? Or 0? Or a string?

else

num = 81

if num % 2 == 0
  puts "This is an even number. YAY!"
else
  puts "This is not an even number."
end

# => "This is not an even number."

Else is a fallback: it only executes if the other conditional statments return false.

Because this is a catchall statement, you can sometimes get unexpected results. What if we only want this statement to work with positive numbers? We need to build in more conditions.

elsif

num = -2

if num % 2 == 0
  puts "This is an even number. YAY!"
elsif num <= 0
  puts "This number is poopy."
else
  puts "This is probably an odd number."
end

# => "This is an even number. YAY!"

WAT?!

Order matters! The first match, not best match, is returned.

num = -2

if num <= 0
  puts "This number is poopy."
elsif num % 2 == 0
  puts "This is an even number. YAY!"
else
  puts "This is probably an odd number."
end

# => "This number is poopy."

This code looks a lot better. Any number less than or equal to 0 will tells us that it is poopy. We can add tons more conditionals in here if we want to.

But wait - there is something funky here. Why is it telling us the number if even when the second conditional is a better match?

Order is very important for conditionals. As soon as a condition is true, the code stops checking for anything else. It doesn't stop and check for the best match, it returns the first match.

Exercises

  • Make an array of numbers and iterate over it to print out results whether a number is even or odd

Writing your own methods

Writing your own methods

What is a method?

Methods are chunks of code that you can reuse so you don't have to type the same thing over and over and over again.

You actually already know what methods are. Remember .delete! and .delete? Those are methods for strings.

Writing your own method

... is surprisingly easy!

The anatomy of a method

def taco_party
  puts "WE LIKE TO PARTY ALL THE TIME"
  puts "PARTY ALL THE TIMEEEE"
  puts "EAT TACOS ALL THE TIME!"
end

taco_party
taco_party
taco_party

This method has no arguments.

What are arguments?

Methods with arguments

Remember our numbers conditional from earlier?

def number_biography(num)
  if num <= 0
    puts "This number is poopy."
  elsif num % 2 == 0
    puts "This is an even number. YAY!"
  else
    puts "This is probably an odd number."
  end
end

number_biography(-2)
# => "This number is poopy."

number_biography(2)
# => "This is an even number. YAY!"

Methods can have more than 1 argument

OMG WHAT IS HAPPENING?!

Keep calm and code on.

Ok, a real example

def salutations(greeting, name)
  puts "#{greeting}, #{name.upcase}. Give me a hug!"
end

salutations("Goodbye", "Spike")
# => "Goodbye, SPIKE. Give me a hug!"

salutations("Oh heyyyyyy", "Angel")
# => "Oh heyyyyyy, ANGEL. Give me a hug!"

Getting RUL RUL fancy

You can use a variable as an argument.

OMG, I KNOW RIGHT?

Variables and Return Values

def introduce(name, food)
  greet = "Hello, this is #{name}. "
  yummy = "#{name}'s favorite food is #{food}."
  puts greet + yummy
end

me = "Liz"
foodz = "TACOS"

introduce(me, foodz)
# => "Hello, this is Liz. Liz's favorite food is TACOS."

Exercises

  • Write a method that takes more than 1 argument and returns a sentence composed of all the arguments.
  • Write a method that uses modulo.
  • Write a multiple-line method with a return statement.
  • Write a method that takes an array as an argument. *

 

* YOU SO FANCY

YOU DID IT! YAYYYY!!!

Learning more....

This book is legit.

Free! Codecademy.com

Cheap! TeamTreehouse.com

Cheap! CodeSchool.com