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}”}