CodeAcademy Ruby Basics Flashcards

1
Q

Types of data in Ruby?

A

String, Numbers, Booleans

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a Modulo, and what is its sign?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Use if, else, and print

A
if 3>2
print "3 is big!"
else
print "We're retarded."
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
Where's the Error (1):
If 3>2
print "3 is big!"
else
print "We're retarded."
end
A

“If” is capitalized; it needs to be “if”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Use elsif to add more than two options to an if/else statement: think greater than, equal, and less than.

A
if x>y
print "X rocks."
elsif y>x
print "Y rocks."
else
print "Y equals X!"
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
Find Error (1):
if x>y
print "X rocks."
elseif y>x
print "Y rocks."
else
print "Y equals X!"
end
A

“elseif” doesn’t exist, it’s “elsif”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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

A
hungry = false
unless hungry
puts "Writing code!"
else 
puts "Eating, fools!"
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Set the variable my_num to the value 100

A

my_num = 100

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

If you wanted the words Hello to show up only if 3>2, then what would you write?

A

if 3>2
Print “Hello.”
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is equals to in Ruby?

A

==

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is not equal to in Ruby?

A

!=

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Less than or equal to and greater than or equal to?

A

=

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does && mean and what are the four options?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does || mean and what are the four options?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does ! mean and what are the four options?

A

Finally, Ruby has the boolean operator not (!). ! makes true values false, and vice-versa.

!true # => false
!false # => true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you get input from the reader; like getting their name?

A

print “What is your name?”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

So, you asked a question, like “What’s your first name?”, but how do we declare that information as the variable first_name?

A

print “What’s your name?”

first_name = gets.chomp

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does “gets” accomplish?

A

gets is the Ruby method that gets input from the user.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Why does the method .chomp accomplish?

A

When getting input, Ruby automatically adds a blank line (or newline) after each bit of input; chomp removes that extra line.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

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.”?

A
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}".
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

String interpolation. What does it look like and what does it accomplish?

A
#{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".
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What should you think when you see ! after a method?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the method to capitalize something?

A

.capitalize

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Let’s say you were trying to reproduce daffy duck’s impediment on someone’s first name; what would you do?

A
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}."
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q
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}."
A

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….

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

See if the string “Morgan” includes a “m”; will it? Why or why not?

A

“Morgan”.include? “m” and it won’t because capitalization matters!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

change all “m”s in a string set equal to name to “n”

A

name.gsub!(/m/, “n”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q
Find the two problems:
counter = 1
while counter = >12
print counter
counter = counter + 1
end
A

while counter = >12

should be while counter < 12

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Count to 11 using the while loop

A
counter = 1
while counter < 12
print counter
counter = counter + 1
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Use while to count from 0 to 5

A

i = 0
while i < 5
puts i
i = i + 1

end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Use until to count from 1-10

A
counter = 1
until counter == 10
  puts counter
  counter = counter + 1
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What’s a shortcut for counter = counter + 1

A

count += 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Use for the loop to to count from 1-9

A

for num in 1…10
puts num
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What’s the difference between for num in 1..10 and for num in 1…10?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

use the number iterator to count from 1 to 5

A

for num in 1..5
puts num
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

You can repeat actions in what two ways?

A

Using loops and iterators

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Curly braces {} are compared to what?

A

In Ruby, curly braces ({}) are generally interchangeable with the keywords do (to open the block) and end (to close it).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

How would you create an infinite loop saying hello world?

A

loop { print “Hello, world!” }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Use the loop do/{} method to count from 1 to 5

A
i = 0
loop do
  i += 1
  print "#{i}"
  break if i > 5
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

how do you make sure your loops don’t go forever?

A

break if and then set a condition

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Write code that lists from 19 to 0 that skips using the iterator loop that skips evens

A
i = 20
loop do
  i -= 1
  next if i % 2 == 0
  print "#{i}"
  break if i <= 0
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

Write code that lists from 19 to 0 that skips using the iterator loop that skips odds

A
i = 20
loop do
  i -= 1
  next if i % 2 != 0
  print "#{i}"
  break if i <= 0
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What is an array?

A

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].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What are curly braces, brackets, and parentheses used for?

A

Curly Braces:

1) String Interpolation #{VARIABLES, which will be replaced by VALUE}
2) do … end with iterators

Parentheses:
.gsub(/whatlooking/, “replaced with”)

Brackets:
Arrays

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

set the array my_array to include 1 through 5

A

my_array = [1, 2, 3, 4, 5]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Use the iterator .each method to print out double this array: my_array = [1, 2, 3, 4, 5]

A
my_array = [1, 2, 3, 4, 5]
my_array.each do |x|
x *=2
print "#{x}"
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Puts versus Print

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q
Where are the errors (2):
my_array = [1, 2, 3, 4, 5]
my_array do |x|
x *=2
print #{x}
end
A

1st) second line needs to read my_array.each do |x|

2nd) second to last line needs to be “#{x}”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

Using the .times iterator print out Chunky Bacon ten times

A

10.times { print “Chunky bacon!” }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

Create a program that is given text and is told which words to redact and then does so.

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

How do you divide a sentence into a list of words? In other words, how do you take a string and return an array?

A

StringName.split(“ “)
Which is basically saying for the particular string named String Name, every time there’s a space split up the string text

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What’s a delimiter?

A

stringname.split(“,”)

the comma is the delimiter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

When do you need to use “end”

A

When you began a process that is now finished; for example for a method like .each and a if entry

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q
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
A

if x = redact

should be if x == redact

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q
Where's the error:
if 3>2
print "Hi World."
elsif 2>3
print "Nonsense abounds."
else 
print "...are you even paying attention?"
A

you don’t “end” the if

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

What’s the error?

prints “What’s your name?”

A

print not prints

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q
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}"."
A

No quotation marks needed for #{variable}, but don’t forget the #!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q
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
A

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?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q
Problem if you're trying to count from 1 to 11, two potential solution:
i = 1
while i < 12
i += 1
print i 
end
A

it will start at 2, unless you switch print i with i += 1 or you start with i = 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q
Find error: 
i = 1
until i = 11
print i
i += 1
end
A

i is set to 11 rather than being equal to 11; use ==

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

Create an array with numbers 1-4 titled array

A

array = [1, 2, 3, 4]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

What’s the index of an array?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

Given array = [1, 2, 4, 4], how would you access the element “2” using its index?

What would you call this?

A

array = [1, 2, 4, 4]
array[1]

This is called access by index or index by offset.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What can an array be made of?

A

Any of the three types of ruby code: string, booleans, and numbers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

Arrays made up of arrays are called what?

A

Multidimensional arrays

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

Create an array of arrays and then print it in its 2-dimensional form

A

array= [[0,0],[0,0],[0,0],[0,0]]
array.each { |x|
puts “#{x}\n” }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

What is a hash?

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

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

A

hash = {“name” => “Morgan”,
“age” => 25,
“hungry?” => true
}

puts hash[“name”]
puts hash[“age”]
puts hash[“hungry?”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

What are the errors?
hash = {“name” => “Morgan”,
“age” = 25,
“hungry?” = true}

puts[“name”]
puts[“age”]
puts[“hungry?”]

A

you have to say
puts hash[“key”]
age and hungry are missing the =>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

Create a hash called pets using a method other than the literal notation

A

pets = Hash.new

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q
Find the error:
i = 20
loop {
i -= 1
if i%2 == 0 
skip i
else
print "#{i}"
break if i<=0}
A

skip doesn’t exist, you mean “next”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q
i = 20
loop {
i -= 1
next i%2 == 0 
print "#{i}"
break if i<=0}
A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q
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
A

The first prints 2-9

The second print 1-9

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

i = 1
If the series goes:
modification
print

how is that different from

print
modification

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

What the issue with next if?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q
Find the error and explain it:
i = 20
loop { print "#{i}"
i -= 1
next if i%2 != 0
break if i<0}
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q
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}"!"
A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q
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
A

it should be words.each do |x|
then if x == redact with no each and with the extra =
print x + “ “

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

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.

A

pets = Hash.new

pets [“Wascally Wabbit”] = “cat”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

Given pets = Hash.new
pets [“Wascally Wabbit”] = “cat”

access the value of Wascally Wabbit

A

pets = Hash.new
pets [“Wascally Wabbit”] = “cat”
puts pets[“Wascally Wabbit”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

Create array and use the each iterator to print out each element, putting one on each line

A

letters = [a, b, c]
letters.each { |x|
puts “#{x}”}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

Problem?
letters = [a, b, c]
letters.each { |x|
puts {“#x”}

A

a, b, and c are are string but you forgot to put them in quotations

83
Q

Create a 2d array where each array makes up the cheese and meat of a sandwich.
Then iterate over an array of arrays

A
s = [["ham", "swiss"], ["turkey", "cheddar"]]
s.each do |x|
x.each do |y|
puts y
end
end
84
Q
Find Errors
s = [["meat1", "cheese1"], ["meat2", "cheese2"]]
s.each { |x| 
x.each {|y|
puts x, y}}
A

no need to put x, y; instead just put y because it refers back to x which refers back to s.

85
Q
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

A
secret_identities = { "The Batman" => "Bruce Wayne",
  "Superman" => "Clark Kent",
  "Wonder Woman" => "Diana Prince",
  "Freakazoid" => "Dexter Douglas"
}

secret_identities.each {|key, value| puts “#{key}: #{value}”}

86
Q
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

A
secret_identities = { "The Batman" => "Bruce Wayne",
  "Superman" => "Clark Kent",
  "Wonder Woman" => "Diana Prince",
  "Freakazoid" => "Dexter Douglas"
}

secret_identities.each {|x, y|
puts y}

87
Q

frequencies = Hash.new(0)

What does the 0 represent?

A

The 0 is the default value of a frequency or of the elements of the array, to be more specific.

88
Q
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}
A

second x at end should be bracketed not piped

89
Q
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}
A

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.

90
Q
Find problems:
puts "Gimme words?"
words = gets.chomp
array = words.split(" ")
frequency = Hash.new(0)
array.each { |x| frequency{x}+= 1}
A

second x should be bracketed not curly bracketed

91
Q

assuming frequency is a hash, what does frequency.search_by accomplish?

A

Turns this hash into an array and lists it from lowest value to highest value

92
Q

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
A
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}
93
Q

What is a “method”?

A

A method is a reusable section of code written to perform a specific task in a program.

94
Q

Why do you separate code into methods? Three reasons.

A

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.

95
Q

What does def prime mean?

A

It means your defining the method prime

96
Q

What are the three parts of a method?

A

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.

97
Q

How do you call a method?

A

You just write it’s name

98
Q

What is the argument and what is the parameter of a method?

A

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.
99
Q

Use the splat method to make three different people say the same thing.

Alice: Hello!
Bob: Hello!
Carl: Hello!

A
def say(what, *people)
  people.each{|person| puts "#{person}: #{what}"}
end
say "Hello!", "Alice", "Bob", "Carl"
# Alice: Hello!
# Bob: Hello!
# Carl: Hello!
100
Q

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.

A
def greeter(name)
   return "Hello, #{name}"
end
def by_three?(n)
   if n %3 == 0
   return true
   else
   return false
end
end
101
Q

What are blocks like?

A

Nameless methods

102
Q

How do you define blocks?

A

do…end or {}

103
Q

Difference between a block and a method?

A

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.

104
Q

What the most often used method to sort items?

A

.sort

105
Q

What is the combined comparison operator?

A

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).

106
Q

Sort array books in ascending order and then descending order

A
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}
107
Q

What is the importance of rev = false within the parameter section?

def alphabetize (arr, rev=false)
end
A

if you call the method but only identify one parameter, like alphabetize(books) then the second parameter, the boolean, is assumed to be false.

108
Q

What does this say in Ruby?

array.sort! { |item1, item2| item2 item1}

A

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

109
Q

Use the space ship operator (sso) < = > but togther to create a method that alphabetizes both a-z and z-a an array

A
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)
110
Q

Use a method other than the space ship operator to create a method that alphabetizes both a-z and z-a an array

A
def alphabetize (arr, rev=false)
if rev == false
arr.sort 
else
arr.sort.reverse
end
end
array = ["i", "am", "an", "example"]
print alphabetize(array)
111
Q

What are the two non-true values in Ruby, and what do they mean?

A

nil (nothing there) and false (not true)

112
Q

Tell me about symbols.

A

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.

113
Q

How do you get the id of an object in Ruby?

A

the method .object_id

114
Q

What are symbols primarily used for in Ruby?

A

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

115
Q

How do you convert a symbol to a string?

A

using the method .to_s

116
Q

How do you convert a string to a symbol?

A

using the method .to_sym

117
Q

How do you add an element to an array?

A

.push

118
Q

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.

A

strings = [“HTML”, “CSS”, “JavaScript”, “Python”, “Ruby”]
symbols = Array.new
strings.each {|x| symbols.push(x.to_sym)}

119
Q

.to_sym and .intern are both methods to accomplish what?

A

Converting a string to a symbol

120
Q

Hashes are made differently from arrays how?

A
Array = [ ]
Hash = { }
121
Q

How did hash syntax change in Ruby 1.9

A

Instead of hash = {:Beethoven => “Sucked”, :Ferngully => “Rocked”}
it’s hash = {Beethoven: “Sucked”, Ferngully: “Rocked”}

122
Q
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.

A
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}
123
Q

What does .select do?

A

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}
124
Q

How would you iterate over just a key or value in a hash?

A

.each_key

.each_value

125
Q

What the issue?
movies = {The Rebound: 4,
“Sin City” => 3,
Twilight: 2}

A

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}

126
Q

Outline the if/else and case differences

A

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:

127
Q

How do you convert a string into an integer?

A

.to_i

128
Q

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.

A
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
129
Q

Find the error:
if true puts “It’s true!
end

A

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

130
Q

One line unless phrase?

A

life_is_awesome = false

puts “Life can get better.” unless life_is_awesome == true

131
Q

What’s the ternary conditional expression?

A

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

132
Q

Create a ternary expression using 3>4

A

puts 3 < 4 ? “3 is less than 4!” : “3 is not less than 4.”

133
Q

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

A
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
134
Q

What’s the conditional assign operator and what does it mean?

A

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.

135
Q

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

A

Cat’s Cradle

Cat’s Cradle

136
Q

When do we use .return

A

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.

137
Q

What if we don’t put a return statement in our method definition?

A

Ruby’s methods will return the result of the last evaluated expression.

138
Q

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

A

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}

139
Q

Write out 95 to 100 using .upto

A

95.upto(100) {|num| print num, “ “ }

140
Q

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!)

A

“L”.upto(“P”) {|let| puts let, “ “ }

Common errors: forgetting the “ “ basically everywhere, putting print instead of puts

141
Q

What does .respond_to? do?

A

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.

142
Q

What is the concatenation operator?

A
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"
143
Q

What are the two different ways to add a variable value into a string?

A
drink = "espresso"
"I love " + drink
# ==> I love espresso
"I love " << drink
# ==> I love espresso
144
Q

How would you add a non-string value into a string?

A

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.
145
Q

What is refactoring?

A

Just a fancy way of saying we’re improving the structure or appearance of our code without changing what it actually does.

146
Q

Refactor this code into one line:

if 1 < 2
puts “One is less than two!”
end

A

puts “One is less than two!” if 1 < 2

147
Q
if 1 < 2
  puts "One is less than two!"
else
  puts "One is not less than two."
end
A

puts 1 < 2? “One is less than two!” : “One is not less than two.”

148
Q

Problem?

3.times puts “I’m a refactoring master!”

A

You need {} around the puts statement

3.times {puts “I’m a refactoring master!”}

149
Q
Problem?
def say(greeting, *name)
name.each {|x| puts "#{greeting} x"}
end
puts say(Hi, Bob, Jill)
A

x needs to be interpolated in the string like greeting
put “ “ around the strings within the argument
and
there is no need for puts

150
Q

Problem?
array = [1, 2]
array.push[3]
puts array

A

array.push(3)

151
Q
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)

A

not .each, but .sort

in your second array.sort you threw in a close end bracket for no damn reason

152
Q

How do you create a new array?

A

array = Array.new

153
Q

Problem?
strings = [“HTML”, “CSS”, “JavaScript”, “Python”, “Ruby”]
symbols = New.Array
string.each {|x| symbols.push(x.to_sym)}

A

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

154
Q

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)
A
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

155
Q

Terminal Moments:

How do you open the terminal?

A

Window + R

run cmd

156
Q

Terminal Moments:

How do you get into ruby?

A

type irb enter

157
Q

Terminal Moments:

How do you get get out of ruby?

A

type exit enter

158
Q

Terminal Moments:

How do you make a new directory in the terminal and then move into it?

A

mkdir WHATEVER

cd WHATEVER

159
Q

Terminal Moments:

How do you view the contents of a directory?

A

dir WHATEVER

160
Q

What is a floating point number?

A

An integer with a decimal

161
Q

How do you do math in Ruby?

A

puts 2+2

162
Q

Problem?

2+2

A

Should says puts 2+2

163
Q

What does \n do?

A

New line

164
Q

What does «PARAGRAPH text text whatever PARAGRAPH accomplish

A

The formatting in terms of lines bookended by the paragraph (but any ALLCAPS phrase words the same) statements is retained

165
Q

What does \ print?

A

Just \

166
Q

Problem?

“I am 6’2” tall.”

A

the 2” tall portion confuses ruby since the “ usually indicates the beginning or end of a string, instead do:

“I am 6’2" tall.”

167
Q

What does " accomplish?

A

It lets ruby now that “ is an actual “ rather than the beginning or end of a string

168
Q

tabby_cat = “\tHi.” does what?

A

When you print tabby_cat Hi will be tabbed in

169
Q

Terminal Moments:

How do you open the terminal?

A

Window + R

run cmd

170
Q

Terminal Moments:

How do you get into ruby?

A

type irb enter

171
Q

Terminal Moments:

How do you get get out of ruby?

A

type exit enter

172
Q

Terminal Moments:

How do you make a new directory in the terminal and then move into it?

A

mkdir WHATEVER

cd WHATEVER

173
Q

Terminal Moments:

How do you view the contents of a directory?

A

dir WHATEVER

174
Q

What is a floating point number?

A

An integer with a decimal

175
Q

How do you do math in Ruby?

A

puts 2+2

176
Q

Problem?

2+2

A

Should says puts 2+2

177
Q

What does \n do?

A

New line

178
Q

What does «PARAGRAPH text text whatever PARAGRAPH accomplish

A

The formatting in terms of lines bookended by the paragraph (but any ALLCAPS phrase words the same) statements is retained

179
Q

What does \ print?

A

Just \

180
Q

Problem?

“I am 6’2” tall.”

A

the 2” tall portion confuses ruby since the “ usually indicates the beginning or end of a string, instead do:

“I am 6’2" tall.”

181
Q

What does " accomplish?

A

It lets ruby now that “ is an actual “ rather than the beginning or end of a string

182
Q

tabby_cat = “\tHi.” does what?

A

When you print tabby_cat Hi will be tabbed in

183
Q
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)
A

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

184
Q
Problem?
print "Give me words!"
text = gets.chomp
words = text.split(" ")
distribution = Hash.new(0)
words.each {
    |x| distribution.push(x)+1
    }
A

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}

185
Q

How do you empty a file?

A

.truncate

186
Q

How do you write stuff to a file?

A

write(stuff)

187
Q

Why do we use STDIN?

A

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.

188
Q

What does this mean?

user = ARGV.first

A

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.

189
Q

What would you write if you wanted to read a file that the user inputed?

A

filename = ARGV.first
txt = File.open(filename)
puts txt.read()

190
Q

What does
target = File.open(filename, ‘w’)
mean?

A

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”

191
Q

Let’s say you want to copy from one file to another; how would you go about this?

A

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()

192
Q

What if you want to know whether a file exists, what would you do?

A

File.exists?(NAMEOFFILE)

193
Q

What is the difference between + and «

A

You can use ‘< is created. This can make a huge difference in your memory utilization, if you are doing really large scale string manipulations.

194
Q

What are Regular Expressions or RegExs?

A

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’)

195
Q

What does .match accomplish? What if we wanted more than just the first match?

A

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!

196
Q

Ternory operater, ? and :

A

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
197
Q

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)

A

You need to state

jelly_beans, jars, crates = secret_formula(start_point)

198
Q

.shift versus .pop

A

.pop removes last element of an array while .shift removes first element of an array

199
Q

What’s the difference between

for x in sites do
puts x
end
and

sites.each do |x|
puts x
end

A

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.
200
Q

How would you create a module with a function inside it?

A
module MyStuff
    def MyStuff.apple()
        puts "I AM APPLES!"
    end
end
201
Q

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?

A

mystuff[‘apple’] # get apple from hash
MyStuff.apple() # get apple from the module
MyStuff::TANGERINE # same thing, it’s just a variable

202
Q

How are classes different than modules?

A

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.

203
Q

What is an object?

A

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.

204
Q

What are the hash, module, and class ways to get things from things?

A
# hash style
mystuff['apples']

module style
mystuff.apples()
puts mystuff.tangerine

class style
thing = MyStuff.new()
thing.apples()
puts thing.tangerine