CodeAcademy Ruby Basics Flashcards
Types of data in Ruby?
String, Numbers, Booleans
What is a Modulo, and what is its sign?
Modulo (%), Modulo returns the remainder of division. For example, 25 % 7 would be 4, since 7 goes into 25 3 times with 4 left over.
Use if, else, and print
if 3>2 print "3 is big!" else print "We're retarded." end
Where's the Error (1): If 3>2 print "3 is big!" else print "We're retarded." end
“If” is capitalized; it needs to be “if”
Use elsif to add more than two options to an if/else statement: think greater than, equal, and less than.
if x>y print "X rocks." elsif y>x print "Y rocks." else print "Y equals X!" end
Find Error (1): if x>y print "X rocks." elseif y>x print "Y rocks." else print "Y equals X!" end
“elseif” doesn’t exist, it’s “elsif”
Let’s say you don’t want to eat unless you’re hungry. That is, while you’re not hungry, you write programs, but if you are hungry, you eat. How would you write a program that a) assumes you’re not hungry, b) if you’re not hungry states “Writing code!”, c) if you are hungry states “Eating, fools!”
hungry = false unless hungry puts "Writing code!" else puts "Eating, fools!" end
Set the variable my_num to the value 100
my_num = 100
If you wanted the words Hello to show up only if 3>2, then what would you write?
if 3>2
Print “Hello.”
end
What is equals to in Ruby?
==
What is not equal to in Ruby?
!=
Less than or equal to and greater than or equal to?
=
What does && mean and what are the four options?
The boolean operator and, &&, only results in true when both expression on either side of && are true. Here’s how && works:
true && true # => true
true && false # => false
false && true # => false
false && false # => false
For example, 1 < 2 && 2 < 3 is true because it’s true that one is less than two and that two is less than three.
What does || mean and what are the four options?
Ruby also has the or operator (||). Ruby’s || is called an inclusive or because it evaluates to true when one or the other or both expressions are true. Check it out:
true || true # => true
true || false # => true
false || true # => true
false || false # => false
What does ! mean and what are the four options?
Finally, Ruby has the boolean operator not (!). ! makes true values false, and vice-versa.
!true # => false
!false # => true
How do you get input from the reader; like getting their name?
print “What is your name?”
So, you asked a question, like “What’s your first name?”, but how do we declare that information as the variable first_name?
print “What’s your name?”
first_name = gets.chomp
What does “gets” accomplish?
gets is the Ruby method that gets input from the user.
Why does the method .chomp accomplish?
When getting input, Ruby automatically adds a blank line (or newline) after each bit of input; chomp removes that extra line.
So, let’s say you’ve gathered two pieces of info: first name and where they were born. How do we state at the end of this gathering process, “Your name is Morgan, and you were born in Florida.”?
print "What's your name?" first_name = gets.chomp print "Where were you born?" birthplace = gets.chomp print "Your name is #{first_name}, and you were born in #{birthplace}".
String interpolation. What does it look like and what does it accomplish?
#{VARIABLE, will be replaced with value of variable} NOTICE BRACKETS If you define a variable monkey that's equal to the string "Curious George", and then you have a string that says "I took #{monkey} to the zoo", Ruby will do something called string interpolation and replace the #{monkey} bit with the value of monkey—that is, it will print "I took Curious George to the zoo".
What should you think when you see ! after a method?
Whenever you see !, think: “This method may be dangerous and do something I don’t expect!” In this case, the unexpected part is that the original string gets changed, not a copy.
What is the method to capitalize something?
.capitalize
Let’s say you were trying to reproduce daffy duck’s impediment on someone’s first name; what would you do?
print "What's your first name?" first_name = gets.chomp if first_name.include? "s" first_name.gsub!(/s/, "th") else puts "Nothing to be done here!" end puts "Your name is #{first_name}."
What's the problem here? print "What's your first name?" first_name = gets.chomp if first_name.include? "s" first_name.gsub!(/s/, "th") else puts "Nothing to be done here!" end puts "Your name is #{first_name}."
first_name.gsub(/s/, “th”) needs to have a “!” after first gsub otherwise no change will show up; explanation “name.reverse evaluates to a reversed string, but only after the name.reverse! line does the name variable actually contain the reversed name.” So, by putting ! it actually modifies the given object. Still unclear on what exactly is happening without a ! then….
See if the string “Morgan” includes a “m”; will it? Why or why not?
“Morgan”.include? “m” and it won’t because capitalization matters!
change all “m”s in a string set equal to name to “n”
name.gsub!(/m/, “n”)
Find the two problems: counter = 1 while counter = >12 print counter counter = counter + 1 end
while counter = >12
should be while counter < 12
Count to 11 using the while loop
counter = 1 while counter < 12 print counter counter = counter + 1 end
Use while to count from 0 to 5
i = 0
while i < 5
puts i
i = i + 1
end
Use until to count from 1-10
counter = 1 until counter == 10 puts counter counter = counter + 1 end
What’s a shortcut for counter = counter + 1
count += 1
Use for the loop to to count from 1-9
for num in 1…10
puts num
end
What’s the difference between for num in 1..10 and for num in 1…10?
for num in 1…10 means “go up to but don’t include 10.” If we use two dots, this tells Ruby to include the highest number in the range.
use the number iterator to count from 1 to 5
for num in 1..5
puts num
end
You can repeat actions in what two ways?
Using loops and iterators
Curly braces {} are compared to what?
In Ruby, curly braces ({}) are generally interchangeable with the keywords do (to open the block) and end (to close it).
How would you create an infinite loop saying hello world?
loop { print “Hello, world!” }
Use the loop do/{} method to count from 1 to 5
i = 0 loop do i += 1 print "#{i}" break if i > 5 end
how do you make sure your loops don’t go forever?
break if and then set a condition
Write code that lists from 19 to 0 that skips using the iterator loop that skips evens
i = 20 loop do i -= 1 next if i % 2 == 0 print "#{i}" break if i <= 0 end
Write code that lists from 19 to 0 that skips using the iterator loop that skips odds
i = 20 loop do i -= 1 next if i % 2 != 0 print "#{i}" break if i <= 0 end
What is an array?
In Ruby, we can pack multiple values into a single variable using an array. An array is just a list of items between square brackets, like so: [1, 2, 3, 4]. The items don’t have to be in order—you can just as easily have [10, 31, 19, 400].
What are curly braces, brackets, and parentheses used for?
Curly Braces:
1) String Interpolation #{VARIABLES, which will be replaced by VALUE}
2) do … end with iterators
Parentheses:
.gsub(/whatlooking/, “replaced with”)
Brackets:
Arrays
set the array my_array to include 1 through 5
my_array = [1, 2, 3, 4, 5]
Use the iterator .each method to print out double this array: my_array = [1, 2, 3, 4, 5]
my_array = [1, 2, 3, 4, 5] my_array.each do |x| x *=2 print "#{x}" end
Puts versus Print
puts add an extra line while print does not; so if you’re doing a .each method to an array, the puts method will make each part of the array be on its own individual line
Where are the errors (2): my_array = [1, 2, 3, 4, 5] my_array do |x| x *=2 print #{x} end
1st) second line needs to read my_array.each do |x|
2nd) second to last line needs to be “#{x}”
Using the .times iterator print out Chunky Bacon ten times
10.times { print “Chunky bacon!” }
Create a program that is given text and is told which words to redact and then does so.
puts “Text to search through: “
text = gets.chomp
puts “Word to redact: “
redact = gets.chomp
words = text.split(“ “)
words.each do |word| if word != redact print word + " " else print "REDACTED " end end
How do you divide a sentence into a list of words? In other words, how do you take a string and return an array?
StringName.split(“ “)
Which is basically saying for the particular string named String Name, every time there’s a space split up the string text
What’s a delimiter?
stringname.split(“,”)
the comma is the delimiter
When do you need to use “end”
When you began a process that is now finished; for example for a method like .each and a if entry
What Errors: puts "What text we looking at?" text = gets.chomp puts "And what are we redacting today?" redact = gets.chomp array = text.split(" ") array.each do |x| if x = redact print "REDACTED" else print x + " " end end
if x = redact
should be if x == redact
Where's the error: if 3>2 print "Hi World." elsif 2>3 print "Nonsense abounds." else print "...are you even paying attention?"
you don’t “end” the if
What’s the error?
prints “What’s your name?”
print not prints
Errors: print "What's your name?" name = gets.chomp print "Where were you born?" birthplace = gets.chomp puts "Your name is "#{name}" and you were born in "{birthplace}"."
No quotation marks needed for #{variable}, but don’t forget the #!
Find errors: print "What's your name?" name = gets.chomp if name.includes?("s") name.gsub!(\s\, "th") print #{name} else print "Nothing to do here!" end
name.include? “s” - no need for ()
name.gsub!(/s/, “th”) - not \!
you won’t see anything, you need to put or print a string and then add the string interpolation!
name.include? not name.includes?
Problem if you're trying to count from 1 to 11, two potential solution: i = 1 while i < 12 i += 1 print i end
it will start at 2, unless you switch print i with i += 1 or you start with i = 0
Find error: i = 1 until i = 11 print i i += 1 end
i is set to 11 rather than being equal to 11; use ==
Create an array with numbers 1-4 titled array
array = [1, 2, 3, 4]
What’s the index of an array?
Here’s something interesting about arrays: each element in the array has what’s called an index. The first element gets index 0, the next gets index 1, the one after that gets index 2, and so on.
Given array = [1, 2, 4, 4], how would you access the element “2” using its index?
What would you call this?
array = [1, 2, 4, 4]
array[1]
This is called access by index or index by offset.
What can an array be made of?
Any of the three types of ruby code: string, booleans, and numbers
Arrays made up of arrays are called what?
Multidimensional arrays
Create an array of arrays and then print it in its 2-dimensional form
array= [[0,0],[0,0],[0,0],[0,0]]
array.each { |x|
puts “#{x}\n” }
What is a hash?
But what if we want to use numeric indices that don’t go in order from 0 to the end of the array? What if we don’t want to use numbers as indices at all? We’ll need a new array structure called a hash.
Hashes are sort of like JavaScript objects or Python dictionaries. If you haven’t studied those languages, all you need to know that a hash is a collection of key-value pairs. Hash syntax looks like this:
hash = { key1 => value1, key2 => value2, key3 => value3 } Values are assigned to keys using =>. You can use any Ruby object for a key or value.
Create a hash with keys name (a string), age (number), and hungry (boolean) and values Morgan 25 true and then print each value using each key, hungry? and values Morgan 25 true and then print each value using each key
hash = {“name” => “Morgan”,
“age” => 25,
“hungry?” => true
}
puts hash[“name”]
puts hash[“age”]
puts hash[“hungry?”]
What are the errors?
hash = {“name” => “Morgan”,
“age” = 25,
“hungry?” = true}
puts[“name”]
puts[“age”]
puts[“hungry?”]
you have to say
puts hash[“key”]
age and hungry are missing the =>
Create a hash called pets using a method other than the literal notation
pets = Hash.new
Find the error: i = 20 loop { i -= 1 if i%2 == 0 skip i else print "#{i}" break if i<=0}
skip doesn’t exist, you mean “next”.
i = 20 loop { i -= 1 next i%2 == 0 print "#{i}" break if i<=0}
next is insufficient, it’s next if
and break if i<=1
it does the final print and then breaks rather than breaking w/out printing when that criteria is met
What's the difference between: i = 1 until i == 10 i += 1 print "#{i}" end
and
i = 1 until i == 10 print "#{i}" i += 1 end
The first prints 2-9
The second print 1-9
i = 1
If the series goes:
modification
print
how is that different from
print
modification
in the first case, the starting number will not be 1, instead it will be whatever number is the result of the first modification
in the second case, the starting number will be 1 and the second number created will take advantage of the modifcations
What the issue with next if?
It needs to after a print or puts command or it’s useless, but this can quickly turn the entire thing into an unending sequence unless it’s put after a modification sequence like i += 1 so it can successfully move on
Find the error and explain it: i = 20 loop { print "#{i}" i -= 1 next if i%2 != 0 break if i<0}
Two errors:
First, the print needs to be after the modification and exception entry rather than before
Second, the break if needs to be BEFORE the print or we’ll print past 0.
Find the errors: print "Name?" name = gets.chomp name.include? "s" name.gsub! (/s/, "th") else print "Nothing to do here!" end print "Your name is "#{name}"!"
1st: You forgot the IF clause!
2nd: After a method, don’t leave a space. So, include?”s” and .gsub!(/th/, “s”)
3rd: “#[i}” is necessary for a string to be produced, but if the #{i} is already in a string, then the parentheses become unnecessary
What's the problem?: print "Text?" text = gets.chomp print "Redact?" text = gets.chomp words = text.split(" ") words do |x| if x.each = redact print "REDACT" else print x end end
it should be words.each do |x|
then if x == redact with no each and with the extra =
print x + “ “
Adding to a hash created with literal notation involves simply adding another has, but let’s say you created the hash pets using Hash.new. Add Wascally Wabbit (key the cat (value) to that hash.
pets = Hash.new
pets [“Wascally Wabbit”] = “cat”
Given pets = Hash.new
pets [“Wascally Wabbit”] = “cat”
access the value of Wascally Wabbit
pets = Hash.new
pets [“Wascally Wabbit”] = “cat”
puts pets[“Wascally Wabbit”]
Create array and use the each iterator to print out each element, putting one on each line
letters = [a, b, c]
letters.each { |x|
puts “#{x}”}
Problem?
letters = [a, b, c]
letters.each { |x|
puts {“#x”}
a, b, and c are are string but you forgot to put them in quotations
Create a 2d array where each array makes up the cheese and meat of a sandwich.
Then iterate over an array of arrays
s = [["ham", "swiss"], ["turkey", "cheddar"]] s.each do |x| x.each do |y| puts y end end
Find Errors s = [["meat1", "cheese1"], ["meat2", "cheese2"]] s.each { |x| x.each {|y| puts x, y}}
no need to put x, y; instead just put y because it refers back to x which refers back to s.
Given: secret_identities = { "The Batman" => "Bruce Wayne", "Superman" => "Clark Kent", "Wonder Woman" => "Diana Prince", "Freakazoid" => "Dexter Douglas" }
create a list where on each line you have a template that produces, for example, The Batman: Bruce Wayne
secret_identities = { "The Batman" => "Bruce Wayne", "Superman" => "Clark Kent", "Wonder Woman" => "Diana Prince", "Freakazoid" => "Dexter Douglas" }
secret_identities.each {|key, value| puts “#{key}: #{value}”}
Given: secret_identities = { "The Batman" => "Bruce Wayne", "Superman" => "Clark Kent", "Wonder Woman" => "Diana Prince", "Freakazoid" => "Dexter Douglas" }
print out their secret identities, one to each line
secret_identities = { "The Batman" => "Bruce Wayne", "Superman" => "Clark Kent", "Wonder Woman" => "Diana Prince", "Freakazoid" => "Dexter Douglas" }
secret_identities.each {|x, y|
puts y}
frequencies = Hash.new(0)
What does the 0 represent?
The 0 is the default value of a frequency or of the elements of the array, to be more specific.
Where's the error of thought? puts "Give me some data!" text = gets.chomp words = text.split(" ") frequencies = Hash.new(0) words.each {|x| frequencies|x| += 1}
second x at end should be bracketed not piped
What does the last line of this code mean? puts "Give me some data!" text = gets.chomp words = text.split(" ") frequencies = Hash.new(0) words.each {|x| frequencies[x] += 1}
Break it down and it’ll make a little more sense. You have a hash called frequencies that you are putting words and numbers into. The words are the keys, and the count of how many times that word appears is the value.
So, when you say frequencies[word] what is the return value? You’re accessing the value stored using the value of whatever the word variable is, so it’s going to be the count. The += 1 bit just says “take this value and increment it by one”. It’s no different than saying:
num_times_so_far = frequencies[word]
num_times_so_far = num_times_so_far + 1
frequencies[word] = num_times_so_far
This is just a one-liner for the above block of code. You’re still getting the value for the key, incrementing it, and then reassigning that value for the same key.
Find problems: puts "Gimme words?" words = gets.chomp array = words.split(" ") frequency = Hash.new(0) array.each { |x| frequency{x}+= 1}
second x should be bracketed not curly bracketed
assuming frequency is a hash, what does frequency.search_by accomplish?
Turns this hash into an array and lists it from lowest value to highest value
In this project, we’ll build a program that takes a user’s input, then builds a hash from that input. Each key in the hash will be a word from the user; each value will be the number of times that word occurs. For example, if our program gets the string “the rain in Spain falls mainly on the plain,” it will return
the 2 falls 1 on 1 mainly 1 in 1 rain 1 plain 1 Spain 1 A visual representation of data like this is called a histogram
puts "Gimme words?" text = gets.chomp words = text.split(" ") frequency = Hash.new(0) words.each { |x| frequency[x]+= 1} frequency = frequency.sort_by {|x,y| y} frequency.each {|x, y| puts x + " " +y.to_s}
What is a “method”?
A method is a reusable section of code written to perform a specific task in a program.
Why do you separate code into methods? Three reasons.
If something goes wrong in your code, it’s much easier to find and fix bugs if you’ve organized your program well. Assigning specific tasks to separate methods helps with this organization.
By assigning specific tasks to separate methods (an idea computer scientists call separation of concerns), you make your program less redundant and your code more reusable—not only can you repeatedly use the same method in a single program without rewriting it each time, but you can even use that method in another program.
When we learn more about objects, you’ll find out there are a lot of interesting things we can do with methods in Ruby.
What does def prime mean?
It means your defining the method prime
What are the three parts of a method?
The header, which includes the def keyword, the name of the method, and any arguments the method takes. (We’ll get to arguments in the next section)
The body, which is the code block that describes the procedures the method carries out. The body is indented two spaces by convention (as with for, if, elsif, and else statements)
The method ends with the end keyword.
How do you call a method?
You just write it’s name
What is the argument and what is the parameter of a method?
def square(n)
puts n ** 2
end
and call it like this:
square(12) # ==> prints "144" The argument is the piece of code you actually put between the method's parentheses when you call it, and the parameter is the name you put between the method's parentheses when you define it. For instance, when we defined square above, we gave it the parameter n (for "number"), but passed it the argument 12 when we called it.
Use the splat method to make three different people say the same thing.
Alice: Hello!
Bob: Hello!
Carl: Hello!
def say(what, *people) people.each{|person| puts "#{person}: #{what}"} end
say "Hello!", "Alice", "Bob", "Carl" # Alice: Hello! # Bob: Hello! # Carl: Hello!
Define two methods in the editor:
A greeter method that takes a single string parameter, name, and returns a string greeting that person. (Make sure to use return and don’t use print or puts.)
A by_three? method that takes a single integer parameter, number, and returns true if that number is evenly divisible by three and false if not. Remember, it’s a Ruby best practice to end method names that produce boolean values with a question mark.
def greeter(name) return "Hello, #{name}" end def by_three?(n) if n %3 == 0 return true else return false end end
What are blocks like?
Nameless methods
How do you define blocks?
do…end or {}
Difference between a block and a method?
Method can be used in a variety of situations, while a block comes into existence, does its magic, and then is over. You need to rewrite the code again to create the same effect; it hasn’t been saved.
What the most often used method to sort items?
.sort
What is the combined comparison operator?
It returns 0 if the first operand (item to be compared) equals the second, 1 if first operand is greater than the second, and -1 if the first operand is less than the second.
A block that is passed into the sort method must return either 1, 0, -1. It should return -1 if the first block parameter should come before the second, 1 if vice versa, and 0 if they are of equal weight, meaning one does not come before the other (i.e. if two values are equal).
Sort array books in ascending order and then descending order
books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"] # To sort our books in ascending order, in-place books.sort! { |firstBook, secondBook| firstBook secondBook }
# Sort your books in descending order, in-place below books.sort! {|firstBook, secondBook| secondBook firstBook}
What is the importance of rev = false within the parameter section?
def alphabetize (arr, rev=false) end
if you call the method but only identify one parameter, like alphabetize(books) then the second parameter, the boolean, is assumed to be false.
What does this say in Ruby?
array.sort! { |item1, item2| item2 item1}
In the context of alphabetizing, this says: “Hey Ruby! Sort the array in-place. Whenever you see two items, compare them and put the one further along in the alphabet first.”
Use the space ship operator (sso) < = > but togther to create a method that alphabetizes both a-z and z-a an array
def alphabetize (arr, rev=false) if rev ==true arr.sort {|item1, item2| item2 < = > item1} else arr.sort {|item1, item2| item1 < = > item2} end end array = ["i", "am", "an", "example"] print alphabetize(array)
Use a method other than the space ship operator to create a method that alphabetizes both a-z and z-a an array
def alphabetize (arr, rev=false) if rev == false arr.sort else arr.sort.reverse end end array = ["i", "am", "an", "example"] print alphabetize(array)
What are the two non-true values in Ruby, and what do they mean?
nil (nothing there) and false (not true)
Tell me about symbols.
They’re not strings. They begin looking like this :dog
Further while multiple strings can have the same value, there can only be one symbol for each value.
How do you get the id of an object in Ruby?
the method .object_id
What are symbols primarily used for in Ruby?
As hash keys or for referencing methods
since they can’t be changed once created and only one for each value can exist they take up less memory
How do you convert a symbol to a string?
using the method .to_s
How do you convert a string to a symbol?
using the method .to_sym
How do you add an element to an array?
.push
Given: strings = [“HTML”, “CSS”, “JavaScript”, “Python”, “Ruby”]
Create a new array, symbols.
Use .each to iterate over the strings array and convert each string to a symbol, adding those symbols to symbols.
strings = [“HTML”, “CSS”, “JavaScript”, “Python”, “Ruby”]
symbols = Array.new
strings.each {|x| symbols.push(x.to_sym)}
.to_sym and .intern are both methods to accomplish what?
Converting a string to a symbol
Hashes are made differently from arrays how?
Array = [ ] Hash = { }
How did hash syntax change in Ruby 1.9
Instead of hash = {:Beethoven => “Sucked”, :Ferngully => “Rocked”}
it’s hash = {Beethoven: “Sucked”, Ferngully: “Rocked”}
Given: movie_ratings = { memento: 3, primer: 3.5, the_matrix: 3, truman_show: 4, red_dawn: 1.5, skyfall: 4, alex_cross: 2, uhf: 1, lion_king: 3.5 }
Create a new variable, good_movies, and set it equal to the result of calling .select on movie_ratings, selecting only movies with a rating greater than 3.
movie_ratings = { memento: 3, primer: 3.5, the_matrix: 3, truman_show: 4, red_dawn: 1.5, skyfall: 4, alex_cross: 2, uhf: 1, lion_king: 3.5 } good_movies = movie_ratings.select { |k, v| v>3}
What does .select do?
The .select method takes a block consisting of a key/value pair and an expression for selecting matching keys and values. Here are some examples:
grades = { alice: 100, bob: 92, chris: 95, dave: 97 }
grades.select { |k,v| k > :c } # ==> {:chris=>95, :dave=>97}
grades.select { |k,v| v < 97 } # ==> {:bob=>92, :chris=>95}
How would you iterate over just a key or value in a hash?
.each_key
.each_value
What the issue?
movies = {The Rebound: 4,
“Sin City” => 3,
Twilight: 2}
if you have a space in your Symbol, you can only write it as :”with spaces”, and then you’d have to use a hash rocket, just as you would if the key were not a Symbol at all.
movies = {“The Rebound” => 4,
“Sin City” => 3,
Twilight: 2}
Outline the if/else and case differences
What most beginners don’t realize is that a case statement is not a substitute for an if..else. It can only replace if..else (and indeed be more readable) in a very special case, namely when your condition only depends on the value of a single variable or expression:
How do you convert a string into an integer?
.to_i
Let’s start by creating a program that will keep track of our movie ratings.
It’ll do one of four things: add a new movie to a hash, update the rating for an existing movie, display the movies and ratings that are already in the hash, or delete a movie from the hash. If it doesn’t receive one of those four commands, the program will output some kind of error message.
movies = {Rebound: 4, Sin: 3, Twilight: 2} puts "What would you like to do?" puts "ADD a movie?" puts "DELETE a movie?" puts "UPDATE a movie?" puts "LIST all rated movies?" choice = gets.chomp case choice when "add" print "Title?" title = gets.chomp if movies[title.to_sym].nil? print "Rating?" rating = gets.chomp movies[title.to_sym] = rating.to_i print "Movie has been added!" else print "You already have this movie recorded!" end when "update" print "Title?" title = gets.chomp if movies[title.to_sym] == nil puts "Error." else puts "New rating?" rating = gets.chomp movies[title.to_sym] = rating.to_i print "Update complete!" end when "display" movies.each {|x, y| puts "#{x}: #{y}"} when "delete" print "Title?" title = gets.chomp if movies[title.to_sym].nil? puts "Error." else movies.delete(title) end else puts "Error!" end
Find the error:
if true puts “It’s true!
end
You can only do:
expression if boolean, so
puts “It’s true!” if true
Also, no end is necessary when the if statement is written all on one line
One line unless phrase?
life_is_awesome = false
puts “Life can get better.” unless life_is_awesome == true
What’s the ternary conditional expression?
Instead of an if/else statement, use this; it takes three arguments:
a boolean, an expression to evaluate if the boolean is true, and an expression to evaluate if the boolean is false.
syntax:
boolean ? Do this if true: Do this if false
Create a ternary expression using 3>4
puts 3 < 4 ? “3 is less than 4!” : “3 is not less than 4.”
Create a case where “English” gets response “Hello” and “French” gets response “Bonjour” and otherwise the response is “I don’t know!” two examples needed
case language when "English" puts "Hello" when "French" puts "Bonjour" else puts "I don't know!" end
case language when "English" then puts "Hello" when "French" then puts "Bonjour!" else puts "I don't know!" end
What’s the conditional assign operator and what does it mean?
But what if we only want to assign a variable if it hasn’t already been assigned? For this, we can use the conditional assignment operator: ||=. It’s made up of the or (||) logical operator and the normal = assignment operator.
What happens?
favorite_book = nil
puts favorite_book
favorite_book ||= “Cat’s Cradle”
puts favorite_book
favorite_book ||= “Why’s (Poignant) Guide to Ruby”
puts favorite_book
Cat’s Cradle
Cat’s Cradle
When do we use .return
We know that methods in Ruby can return values, and we ask a method to return a value when we want to use it in another part of our program.
What if we don’t put a return statement in our method definition?
Ruby’s methods will return the result of the last evaluated expression.
What’s the issue?
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.each {|x| if x%2==0
puts “#{x}”}
either puts first and then if
or put the equation after if within a () and type “then” before the puts
my_array.each {|x| puts “#{x}” if x%2==0
}
OR
my_array.each {|x| puts “#{x} if x.even?
}
OR
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.each {|x| if (x % 2 ==0) then puts x end}
Write out 95 to 100 using .upto
95.upto(100) {|num| print num, “ “ }
Try using .upto to puts the capital letters “L” through “P”. (Make sure to use puts and not print, so each letter is on its own line!)
“L”.upto(“P”) {|let| puts let, “ “ }
Common errors: forgetting the “ “ basically everywhere, putting print instead of puts
What does .respond_to? do?
Remember when we mentioned that symbols are awesome for referencing method names? Well, .respond_to? takes a symbol and returns true if an object can receive that method and false otherwise. For example,
[1, 2, 3].respond_to?(:push)
would return true, since you can call .push on an array object. However,
[1, 2, 3].respond_to?(:to_sym)
would return false, since you can’t turn an array into a symbol.
What is the concatenation operator?
Instead of typing out the .push method name, you can simply use <<< 4 # ==> [1, 2, 3, 4] Good news: it also works on strings! You can do:
"Yukihiro " << "Matsumoto" # ==> "Yukihiro Matsumoto"
What are the two different ways to add a variable value into a string?
drink = "espresso" "I love " + drink # ==> I love espresso "I love " << drink # ==> I love espresso
How would you add a non-string value into a string?
Turn it into a string first, of course!
age = 26 "I am " + age.to_s + " years old." # ==> "I am 26 years old." "I am " << age.to_s << " years old." # ==> "I am 26 years old."
or
use string interpolation (more eloquent) age = 26 drink = "espresso" "I love #{drink}." # ==> I love espresso. "I am #{age} years old." # ==> I am 26 years old.
What is refactoring?
Just a fancy way of saying we’re improving the structure or appearance of our code without changing what it actually does.
Refactor this code into one line:
if 1 < 2
puts “One is less than two!”
end
puts “One is less than two!” if 1 < 2
if 1 < 2 puts "One is less than two!" else puts "One is not less than two." end
puts 1 < 2? “One is less than two!” : “One is not less than two.”
Problem?
3.times puts “I’m a refactoring master!”
You need {} around the puts statement
3.times {puts “I’m a refactoring master!”}
Problem? def say(greeting, *name) name.each {|x| puts "#{greeting} x"} end puts say(Hi, Bob, Jill)
x needs to be interpolated in the string like greeting
put “ “ around the strings within the argument
and
there is no need for puts
Problem?
array = [1, 2]
array.push[3]
puts array
array.push(3)
Problem? def alph(array, rev = false) if rev == false array.each {|x, y| x y} else array.each {|x, y|} y x} end
array2= [1, 2, 3]
alph(array2)
not .each, but .sort
in your second array.sort you threw in a close end bracket for no damn reason
How do you create a new array?
array = Array.new
Problem?
strings = [“HTML”, “CSS”, “JavaScript”, “Python”, “Ruby”]
symbols = New.Array
string.each {|x| symbols.push(x.to_sym)}
strings = [“HTML”, “CSS”, “JavaScript”, “Python”, “Ruby”]
symbols = Array.new
strings.each {|x| symbols.push(x.to_sym)}
string doesn’t exist, it’s strings
New.Array doesn’t exist, it’s Array.new
Problem?
def alph(given, rev = false) if rev == false given.each {|x, y| x y} else given.each.reverse end end hash = [1, 2, 3] alph(hash)
def alph(given, rev = false) if rev == false given.sort else given.sort.reverse end end hash = [1, 2, 3] alph(hash, true)
.sort not .each
and .sort is the method of sorting, so no do is necessary
Terminal Moments:
How do you open the terminal?
Window + R
run cmd
Terminal Moments:
How do you get into ruby?
type irb enter
Terminal Moments:
How do you get get out of ruby?
type exit enter
Terminal Moments:
How do you make a new directory in the terminal and then move into it?
mkdir WHATEVER
cd WHATEVER
Terminal Moments:
How do you view the contents of a directory?
dir WHATEVER
What is a floating point number?
An integer with a decimal
How do you do math in Ruby?
puts 2+2
Problem?
2+2
Should says puts 2+2
What does \n do?
New line
What does «PARAGRAPH text text whatever PARAGRAPH accomplish
The formatting in terms of lines bookended by the paragraph (but any ALLCAPS phrase words the same) statements is retained
What does \ print?
Just \
Problem?
“I am 6’2” tall.”
the 2” tall portion confuses ruby since the “ usually indicates the beginning or end of a string, instead do:
“I am 6’2" tall.”
What does " accomplish?
It lets ruby now that “ is an actual “ rather than the beginning or end of a string
tabby_cat = “\tHi.” does what?
When you print tabby_cat Hi will be tabbed in
Terminal Moments:
How do you open the terminal?
Window + R
run cmd
Terminal Moments:
How do you get into ruby?
type irb enter
Terminal Moments:
How do you get get out of ruby?
type exit enter
Terminal Moments:
How do you make a new directory in the terminal and then move into it?
mkdir WHATEVER
cd WHATEVER
Terminal Moments:
How do you view the contents of a directory?
dir WHATEVER
What is a floating point number?
An integer with a decimal
How do you do math in Ruby?
puts 2+2
Problem?
2+2
Should says puts 2+2
What does \n do?
New line
What does «PARAGRAPH text text whatever PARAGRAPH accomplish
The formatting in terms of lines bookended by the paragraph (but any ALLCAPS phrase words the same) statements is retained
What does \ print?
Just \
Problem?
“I am 6’2” tall.”
the 2” tall portion confuses ruby since the “ usually indicates the beginning or end of a string, instead do:
“I am 6’2" tall.”
What does " accomplish?
It lets ruby now that “ is an actual “ rather than the beginning or end of a string
tabby_cat = “\tHi.” does what?
When you print tabby_cat Hi will be tabbed in
Problem? alph = [array, rev == false] if rev == false array.sort {|x, y| x y} else array.sort {|x, y| y x} end end array = ["apple", "life"] alph (array, true)
first line is all manners of messed up
def alph (array, rev=false)
for the last line there can be no space before the (
alph(array,true) is what you need
Problem? print "Give me words!" text = gets.chomp words = text.split(" ") distribution = Hash.new(0) words.each { |x| distribution.push(x)+1 }
No need to push, you can just place it automatically. with [] NOT () and +1 not just +
Also, you forgot to sort by highest to lowest frequency
words.each { |x| distribution[x]+= 1}
distribution= distribution.sort_by {|x,y| y}
distribution.each {|x, y| puts x + “ “ +y.to_s}
distribution.sort_by {|x, y| y}
How do you empty a file?
.truncate
How do you write stuff to a file?
write(stuff)
Why do we use STDIN?
Also notice that we’re using STDIN.gets instead of plain ‘ol gets. That is because if there is stuff in ARGV, the default gets method tries to treat the first one as a file and read from that. To read from the user’s input (i.e., stdin) in such a situation, you have to use it STDIN.gets explicitly.
What does this mean?
user = ARGV.first
user = ARGV.first means that when you go to the command line and type Ruby whatever.rb WHATEVER this WHATEVER will be equal to user.
What would you write if you wanted to read a file that the user inputed?
filename = ARGV.first
txt = File.open(filename)
puts txt.read()
What does
target = File.open(filename, ‘w’)
mean?
We open the file but, instead of opening it in default mode which is reading, it open it in writing mode due to the “w”
Let’s say you want to copy from one file to another; how would you go about this?
from_file, to_file = ARGV
script = $0
puts “Copying from #{from_file} to #{to_file}”
# we could do these two on one line too, how? input = File.open(from_file) indata = input.read()
puts “The input file is #{indata.length} bytes long”
puts “Does the output file exist? #{File.exists? to_file}”
puts “Ready, hit RETURN to continue, CTRL-C to abort.”
STDIN.gets
output = File.open(to_file, ‘w’)
output.write(indata)
puts “Alright, all done.”
output. close()
input. close()
What if you want to know whether a file exists, what would you do?
File.exists?(NAMEOFFILE)
What is the difference between + and «
You can use ‘< is created. This can make a huge difference in your memory utilization, if you are doing really large scale string manipulations.
What are Regular Expressions or RegExs?
Regular Expressions or RegExs are a concise and flexible means for “matching” particular characters, words, or patterns of characters. In Ruby you specify a RegEx by putting it between a pair of forward slashes (/). Now let’s look at an example that replaces all the vowels with the number 1:
Example Code:
‘RubyMonk’.gsub(/[aeiou]/,’1’)
What does .match accomplish? What if we wanted more than just the first match?
We covered the art of finding the position of a substring in a previous lesson, but how do we handle those cases where we don’t know exactly what we are looking for? That’s where Regular Expressions come in handy. The String#match method converts a pattern to a Regexp (if it isn‘t already one), and then invokes its match method on the target String object. Here is how you find the characters from a String which are next to a whitespace:
Example Code:
‘RubyMonk Is Pretty Brilliant’.match(/ ./)
[reset]
As you can see in the output, the method just returns the first match rather than all the matches. In order to find further matches, we can pass a second argument to the match method. When the second parameter is present, it specifies the position in the string to begin the search. Let’s find the second character in the string ‘RubyMonk Is Pretty Brilliant’ preceded by a space, which should be ‘P’.
‘RubyMonk Is Pretty Brilliant’.match(/ ./)
[reset] See the Solution
All the complex use cases of this method involve more advanced Regular Expressions, which are outside the context of this lesson. However, on an ending note, if you ever choose to implement a parser, String#match might turn out to be a very good friend!
Ternory operater, ? and :
In Ruby, ? and : can be used to mean “then” and “else” respectively. Here’s the first example on this page re-written using a ternary operator.
def check_sign(number) number > 0 ? "#{number} is positive" : "#{number} is negative" end
Problem?
start_point = 10000
secret_formula(start_point)
puts “With a starting point of: %d” % start_point
puts “We’d have %d jelly beans, %d jars, and %d crates.” % secret_formula(start_point)
You need to state
jelly_beans, jars, crates = secret_formula(start_point)
.shift versus .pop
.pop removes last element of an array while .shift removes first element of an array
What’s the difference between
for x in sites do
puts x
end
and
sites.each do |x|
puts x
end
for is a syntax construct, somewhat similar to if. Whatever you define in for block, will remain defined after for as well:
sites = %w[stackoverflow stackexchange serverfault] #=> ["stackoverflow", "stackexchange", "serverfault"]
for x in sites do puts x end stackoverflow stackexchange serverfault #=> ["stackoverflow", "stackexchange", "serverfault"] x #=> "serverfault" On the other hand, each is a method which receives a block. Block introduces new lexical scope, so whatever variable you introduce in it, will not be there after the method finishes:
sites.each do |y| puts y end stackoverflow stackexchange serverfault #=> ["stackoverflow", "stackexchange", "serverfault"] y NameError: undefined local variable or method `y' for # from (irb):9 from /usr/bin/irb:12:in `' I would recommend forgetting about for completely, as using each is idiomatic in Ruby for traversing enumerables. It also recspects the paradigm of functional programming better, by decreasing chances of side-effects.
How would you create a module with a function inside it?
module MyStuff def MyStuff.apple() puts "I AM APPLES!" end end
How do you use a module in a program and call functions and variables? And how is that different from just getting something from a hash?
mystuff[‘apple’] # get apple from hash
MyStuff.apple() # get apple from the module
MyStuff::TANGERINE # same thing, it’s just a variable
How are classes different than modules?
Here’s why classes are used instead of modules: You can take the above class, and use it to craft many of them, millions at a time if you want, and they won’t interfere with each other. With modules, when you require there is only one for the entire program unless you do some monster hacks.
What is an object?
If a class is like a “mini-module”, then there has to be a similar concept to require but for classes. That concept is called “instantiate” which is just a fancy obnoxious overly smart way to say “create”. When you instantiate a class, what you get is called an object.
What are the hash, module, and class ways to get things from things?
# hash style mystuff['apples']
module style
mystuff.apples()
puts mystuff.tangerine
class style
thing = MyStuff.new()
thing.apples()
puts thing.tangerine