Ruby Crash Course

Girl Develop It

Instructor: Grace Tan

Modified from GDI Austin Ruby on Rails track. Major, major props to Cecy Correa of GDI Austin!

Welcome!

Girl Develop It is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • We are here for you!
  • Every question is important.
  • Help each other.
  • Have fun!

INTRODUCE YOURSELF!

Tell us about yourself.

  • Who are you?
  • What do you hope to get out of the class?
  • What's your favorite thing to do in NYC during the Spring?

History of Ruby

  • Written / Invented by Yukihiro Matsumoto “Matz” in 1995
  • Gained popularity around 2000
  • Ruby on Rails comes out in 2005 and Ruby really explodes in popularity at that time.

Oh hai! I'm Matz!

Why Ruby?

  • It reads like English. The syntax is intuitive.
  • 
    # Java
    for(int i = 0; i < 5; i++)
    
    # Ruby
    5.times do
    			
  • Large, friendly community.
  • Lots of resources available!
  • You can get a web app off the ground quickly.
  • Using Ruby will cost you $0.
  • But also...

Was made for programmer happiness!

Meant to be very readable!

What is Ruby used for?

  • Web development (Rails)
  • iPhone apps (RubyMotion)
  • System Administration (Chef)
  • Testing (Vagrant)
  • Security (Metasploit)

Who is using Ruby?

  • Hulu
  • Funny or Die
  • Groupon
  • Shopify
  • Airbnb
  • WeWork

Working with Ruby

We'll use REPL.IT to run Ruby code.

A quick word on programming...

When you're first learning

As you go on

Programming is...

  • 70% learning / researching
  • 10% actual coding
  • 20% debugging

Okay... I'm exaggerating!

Let's start coding!

https://repl.it

Select "Ruby"

Repl.It


				puts "Hello World!"
				

Does math!


				1 + 1
				

Will evaluate to 2!

You can subtract (-), multiply (*), "divide" (%)

We're coding!

Variables

Just puting "Hello World!" every time is boring. We can store this in a variable!

Programmers are lazy. We like to type very little!


				greeting = "Hello World!"
				

Variables

Variables can store data!

  • Words! (called strings in programming talk)
  • Numbers! (integers and decimals!)
  • True/False! (called booleans in programming talk)

Strings, numbers, and booleans are a subset of Ruby datatypes.

Can combine them with "puts"!

Let's check it out!

DEMO!

Your turn!

Goal:

  • Do some math in Ruby
  • Use "puts" to return text

Go to https://repl.it/HBtw/2

Duration: 5 minutes

Ok, this is cool. But how do I get info from a user?

gets.chomp

Get a user's input


				gets.chomp
				

This grabs the info the user types in...

Can save this to a variable to use the value again!


				response = gets.chomp
				

Let's build a quick program using gets.chomp!

  1. We're going to get the user's name
  2. Get where they're from
  3. Get their favorite animal

Let's build a quick program using gets.chomp!


puts "What is your name?"
name = gets.chomp
puts "Where are you from?"
location = gets.chomp
puts "What is your favorite animal?"
animal = gets.chomp
puts "Got it, your name is " + name
puts "You are from " + location
puts "And your favorite animal is " + animal
				

DEMO!

Your turn!

Goal:

  • Add the q "What's your favorite color?"
  • Use 'puts' gets.chomp to get the response
  • Print out the response using 'puts'

Go to https://repl.it/HBxT/0

Duration: 5 minutes

Let Ruby do the heavy lifting

Helper methods!

  • upcase
  • capitalize
  • swap case
  • reverse
  • length

These are all built-in with Ruby!

'gets' and 'chomp' are also built-in methods as well!

Demo

Can also write your own methods!

Make methods do things!

methods

They take something in and spit something out

Methods

This method takes in a name, and greets the name.


def greeting(name)
	name = name.capitalize
	puts "Hello " + name
end
				

Methods can return values!

Whatever value is on the last line of the method is the return value


def get_date()
	Date.today
end
				

def add_and_times(initial, add, times)
	added_value = initial + add
	added_value * times
end

result = add_and_times(0,1,5)
puts result
				

Your turn!

Goal:

  • Write a method to return the square of any number you pass in
  • use 'puts' to print out the number

Go to https://repl.it/HBxb/7

Duration: 5 minutes

This is pretty boring... let's do more!

Flow Control

Flow Control

Looping

Used when you want to do something multiple times



for i in 0..9 do
    puts "#{i}"
end 

while i < 9 do
	puts i
	i+=1
end
				

'If' Statement

Do something if the test evaluates to true"

"==" means compare!


if animal == "dog"
	puts "bark"
elsif animal == "cat"
	puts "meow"
elsif animal == "snake"
	puts "hiss"
else 
	puts "meep! I don't know what animal type this is :("
end
				

Beware of infinite loops!

DEMO!

Storing data!

  • Arrays
  • Hashes

Arrays

  • Stores things!
  • Numbers!
  • Strings!
  • Other arrays!

Arrays


array_of_stuff = [1, "two", "3", "A"]
				
  • Can call out the whole thing
  • Can call out individual parts

Creating a new array

Can be filled with stuff on initialization!


pet_types = ["cat", "dog", "snake"]
				

Can be empty on initialization


pet_types = []
				

Putting stuff in an array


pet_types << "bird"
				

Putting stuff in an array (method #2!)


pet_types.push("bird")
				

How to take stuff out?

Arrays


pet_types = ["cat", "dog", "snake"]
				

There are different ways to take stuff out

.POP!


pet_types.pop
				

This removes the last thing in the array

It also "returns" that value

Push and POP!

Getting something specific


pet_types[0]
				

pet_types[1]
				

pet_types[2]
				

You can get the value you want depending on where it is in the array

Position is its "index"

BEWARE! Arrays start at "0"

Demo!

Your turn!

Goal:

  • Create an array for the days of the week
  • Get "Tuesday" from the array (hint: what index is it at?)

Go to https://repl.it/HBtl/1

Duration: 5 minutes

Hashes

Hashes

Hashes allow you to store information in "key value" pairs.

Huh?

Hashes


pet = { type: "snake", price: 10 }

vs

pet_type = "snake"
pet_price = 10
				

This helps keep info organized.

What are other things we could store in hashes?


pet = { type: "snake", prices: [10, 15, 20] }
				

Let's use Hashes and Arrays to build a petstore inventory together

Hashes and Arrays


 pet_types = [ 
      {
        name: "snakes",
        price: 10
      },
      {
        name: "cats",
        price: 20
      },
      {
        name: "dogs",
        price: 20
      }
    ]
				

Hashes and Arrays

Getting info out


pet_types[0][:name]
pet_types[0][:price]	
pet_types[1][:name]
pet_types[1][:price]
# etc....
				

So tedious!

More looping!

.each do

You can use .each do to loop through items in an array!


pet_types.each do |pet_type|
	puts pet_type[:name]
	puts pet_type[:price]
end
			

This outputs all of the types and their attributes at once!

Can also use For loops!


for type in pet_types
	puts type[:name]
	puts type[:price]
end
			

Demo!

Your turn!

Goal:

  • Loop through the pet_types array and print out the price with "$" in front of it
  • Hint: .to_s might be needed: https://apidock.com/ruby/Fixnum/to_s

Go to https://repl.it/HByP/1

Duration: 5 minutes

Overwhelmed?
It's ok! We're almost there!

Classes

  • Object-oriented programming!
  • Modeled after “real” things
  • Have properties
  • Can inherit properties

Classes

Let's "model" a cat.

cat

A cat has...

  • a Name
  • it Meows

DEMO!

Sample class


class Cat

	attr :name 

	def initialize(name)
		@name = name
	end

	def talks
		puts "*meowwwww*"
	end
end
			

Class inheritance

cat and kitty

What if you wanted to create a class "Dog", but you knew it would be pretty similar to "Cat"?

Is there a way to "copy" a class?

Why, yes! (Sort of.) You can use sub-classes.

Sub-classes


class Pet
	attr :name 

	def initialize(name)
		@name = name
	end
	
	def talks(noise)
		puts noise
	end
end

class Cat < Pet
	def initialize(name)
		@name = name
	end
	
	def talks
		super("meowwww")
	end
end
			

		class Dog < Pet
			def initialize(name)
				@name = name
			end
			
			def talks
				super("wooofff")
			end
		end
			

You can use the < to symbolize Cat and Dog is a sub-class from Pet.

The stuff available for Pet is available for Cat.

The stuff available for Cat is NOT available for Pet.

Inheritance travels down, not up.

DEMO!

Your turn!

Goal:

  • Write a Class for Snake that inhereits from Pet
  • Implement talk for Snake
  • Add more methods to Pet (ex: sleep, eat) and Snake (ex: shed_skin)
  • Keep it simple! :)

Go to https://repl.it/HBy3/1

Duration: 10 minutes

Time to build our pet shop!

Everyone go to https://repl.it/HBwN/7

Does stuff look familiar???

  • main.rb: Program for user to interface with. Tons of gets.chomp and a 'if' statement!
  • pet.rb: Parent class. Has a loop in the 'play' method! Only new thing is 'sleep'.
  • pet_types.rb: Subclasses. Nothing new here!
  • pet_shop.rb: Has our awesome array of hashes! Has a loop and a if statement

You got this!!

Goal:

  • Go to pet_types.rb and finish the Dog subclass by implementing the initializer and the 'talk' method
  • Go to pet.rb and finish the 'sleep' method. Implement it in a way that will pause the method for 5 seconds while the animal is sleeping. Take a look at the 'play' method for a hint. Use 'puts' at the end to let the user know when the pet has woken up!
  • Go to main.rb file and ad a condition for action == "sleep" in the 'if' statement and call your new sleep function when the user passes in "sleep"

Thank you!

Please help us improve this class by taking this short survey!