On Github feministy / ruby_basics
I am a very nice person who loves:
Sorry about those last two things.
What to expect:
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.
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.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.
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.
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.
ruby, like any good language, has a style guide that can provide you with more information about valid variable names.
Yes!
No!
Wat?
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.
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.
a = 5 b = 10 c = 2 d = c * a - b
* try and blow it up :)
hello.rb:
puts 10 % 5 puts 10 % 3
Terminal:
$ ruby hello.rb # => 0 # => 1this returns the remainder if the first number is divided by the second.
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.
hello.rb:
age = '28' name = 'Liz Abinante' puts name + ' is ' + age
Terminal:
$ ruby hello.rb # => Liz Abinante is 28strings can contain numbers, but you can’t do math with the string-ified number. it will treat it like a string, not a number.
age
name
city
favorite_color
favorite_food
puts name * 15
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
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.
me = "Liz" me.swapcase! puts me #=> "lIZ"
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
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: []
array = ["chickens", "two cents", "ke$ha"] array.length # => 3
you can count the number of things in your array with array.length
array = ["chickens", "two cents", "ke$ha"] array[0] # => "chickens" array[1] # => "two cents" array[2] # => "ke$ha"
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.
taco = ["cheese", "guacamole"] taco << "sour cream" taco << "potato chips" << "jelly beans" # => ["cheese", "guacamole", "sour cream", "potato chips", "jelly beans"]
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.
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"]
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.
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.
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.
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?
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.
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!"
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.
You actually already know what methods are. Remember .delete! and .delete? Those are methods for strings.
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
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!"
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!"
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."
* YOU SO FANCY