I created 346 questions to review Ruby syntax and concepts covered in The Well-Grounded Rubyist by David Black. Each question tests a specific concept in the book.
Some questions are designed to raise errors. The answers listed for those questions would be the appropriate error (e.g., NameError
, ArgumentError
).
Section | Topic | Questions |
---|---|---|
1 | Ruby Basics | 26 |
2 | Objects, Methods, and Local Variables | 17 |
3 | Classes and self |
17 |
4 | Modules, super , and Constant Resolution |
17 |
5 | Private and Protected Methods | 18 |
6 | if , else , and case |
17 |
7 | Loops, Iterators, and Code Blocks | 20 |
8 | Exceptions | 14 |
9 | Built-in Essentials | 26 |
10 | Strings and Symbols | 26 |
11 | Arrays | 48 |
12 | Hashes | 22 |
13 | Ranges and Sets | 27 |
14 | Regular Expressions | 33 |
15 | Procs and Lambdas | 18 |
- Which of the following are ways to create a String object with value "Hello World"? Select all that apply.
- A:
"Hello World"
- B:
String.new("Hello World")
- C:
'Hello World'
- D:
Hello World
- E:
String.new(Hello World)
Answer
A, B, C
- Given
name = "Frodo"
, write aputs
statement that outputs"My dog is named Frodo."
Use string interpolation.
Answer
puts "My dog is named #{name}."
- Create a symbol named
abc
using the literal constructor.
Answer
:abc
- What is returned from executing the following statement?
1 + 2
Answer
3
- What is returned from executing the following statement?
1 * 2
Answer
2
- What is returned from executing the following statement?
5 / 2
Answer
2
- What is returned from executing the following statement?
5 / 2.0
Answer
2.5
- What is returned from executing the following statement?
5.0 / 2.0
Answer
2.5
- What is returned from executing the following statement?
10 % 2
Answer
0
- What is returned from executing the following statement?
10 % 3
Answer
1
- What is output from executing the following statement?
puts "Hello World"
Answer
"Hello World"
- What is returned from executing the following statement?
puts "Hello World"
Answer
nil
- What is returned from executing the following statement?
"Hello World".nil?
Answer
false
- What is returned from executing the following statement?
0.nil?
Answer
false
- What is returned from executing the following statement?
"".nil?
Answer
false
- What is returned from executing the following statement?
false.nil?
Answer
false
- Create an array using the literal constructor consisting of the elements
"a"
,"b"
, and"c"
. Assign it to the local variablearr
.
Answer
arr = ["a", "b", "c"]
- Create a hash using the literal constructor with the key and value pairs (
"one"
,1
), ("two"
,2
), and ("three"
,3
). Assign it to the local variableintegers
.
Answer
integers = {"one" => 1, "two" => 2, "three" => 3}
- What is output from executing the following statement?
puts [1, 2, 3]
Answer
1
2
3
- What is output from executing the following statement?
puts [1, 2, 3].inspect
Answer
[1, 2, 3]
- What is output from executing the following statement?
p [1, 2, 3]
Answer
[1, 2, 3]
- Write a statement that converts the integer
1
to its string representation.
Answer
1.to_s
- Write a statement that converts the string
"1230"
to its integer representation.
Answer
"1230".to_i
- What is returned from executing the following statement?
"123.5".to_f
Answer
123.5
- What is returned from executing the following statement?
"001230".to_i
Answer
1230
- What is returned from executing the following statement?
"123ab23".to_i
Answer
123
- What does the following code output?
a = 5
def my_method
puts a
end
my_method
Answer
NameError (undefined local variable or method a for main:Object)
- What does the following code output?
a = 5
def my_method(a)
puts a
end
my_method(10)
Answer
10
- What does the following code output?
a = 5
def my_method
a = 20
puts a
end
my_method
Answer
20
- What does the following code output?
str = "Hello World"
def my_method(str)
str = ''
end
my_method(str)
puts str
Answer
"Hello World"
- What does the following code output?
str = "Hello World"
def my_method(str)
str = str.upcase
end
my_method(str)
puts str
Answer
"Hello World"
- What does the following code output?
str = "Hello World"
def my_method(str)
str.upcase!
end
my_method(str)
puts str
Answer
"HELLO WORLD"
- What does the following code output?
my_array = [1, 2, 3]
def my_method(arr)
arr << 4
arr[0] = 'hello'
end
my_method(my_array)
p my_array
Answer
["hello", 2, 3, 4]
- What does the following code output?
def my_method(arg1, arg2, arg3)
[arg1, arg2, arg3]
end
p my_method(1, 2)
Answer
ArgumentError (wrong number of arguments (given 2, expected 3))
- What does the following code output?
def my_method(arg1, arg2, arg3)
[arg1, arg2, arg3]
end
p my_method(1, 2, 3, 4)
Answer
ArgumentError (wrong number of arguments (given 4, expected 3))
- What does the following code output?
def my_method(*arg1)
arg1
end
p my_method(1, 2, 3, 4)
Answer
[1, 2, 3, 4]
- What does the following code output?
def my_method(arg1=0, arg2=0)
[arg1, arg2]
end
p my_method(1)
Answer
[1, 0]
- What does the following code output?
def my_method(arg1=0, *arg2, arg3)
[arg1, arg2, arg3]
end
p my_method(1, 2, 3, 4, 5, 6)
Answer
[1, [2, 3, 4, 5], 6]
- What does the following code output?
def my_method(arg1=0, *arg2, arg3=5)
[arg1, arg2, arg3]
end
p my_method(1, 2, 3, 4, 5, 6)
Answer
SyntaxError
when you try to define the method
- What does the following code output?
a = 5
loop do
puts a
break
end
Answer
5
- Given the following code, which of the following statements are true? Select all that apply.
a = 5
# main level
1.times do
# level 1
b = 2
1.times do
# level 2
c = 3
1.times do
# level 3
d = 4
end
end
end
- A. Variable
a
is accessible at the main level. - B. Variable
b
is accessible at the main level. - C. Variable
c
is accessible at the main level. - D. Variable
d
is accessible at the main level. - E. Variable
a
is accessible at level 1. - F. Variable
b
is accessible at level 1. - G. Variable
c
is accessible at level 1. - H. Variable
d
is accessible at level 1. - I. Variable
a
is accessible at level 2. - J. Variable
b
is accessible at level 2. - K. Variable
c
is accessible at level 2. - L. Variable
d
is accessible at level 2. - M. Variable
a
is accessible at level 3. - N. Variable
b
is accessible at level 3. - O. Variable
c
is accessible at level 3. - P. Variable
d
is accessible at level 3.
Answer
A, E, F, I, J, K, M, N, O, P
- What does the following code output?
input = "World"
def say_hello(str)
"Hello" + str
end
def say_hi(str)
str.prepend("Hi ")
end
say_hello(input)
say_hi(input)
puts input
Answer
"Hi World"
- What does the following code output?
def my_method
return "Hello Marian"
"Hello Robin Hood"
end
p my_method
Answer
"Hello Marian"
- What does the following code output?
class Person
def initialize(name)
@name = name
end
end
bob = Person.new("Bob")
puts bob.name
Answer
NoMethodError (undefined method 'name' for #<Person:0x0000556cd4875960 @name="Bob">)
- Which of the following modifications would cause the code to output
"Bob"
? Mark all that apply.
class Person
def initialize(name)
@name = name
end
end
bob = Person.new("Bob")
puts bob.name
- A. Add
attr_reader :name
- B. Add
attr_writer :name
- C. Add
attr_accessor :name
- D. Define a method
def name; @name; end
- E. Define a method
def name; name; end
Answer
A, C, D
- What kind of variable is
@name
?
Answer
instance variable
- What kind of variable is
@@name
?
Answer
class variable
- What does the following code output?
class Person
@@counter = 0
attr_reader :name
def initialize(name)
@name = name
@@counter += 1
end
def self.counter
@@counter
end
end
lisa = Person.new("Lisa")
ruth = Person.new("Ruth")
puts Person.counter
puts lisa.counter
Answer
2
NoMethodError (undefined method 'counter' for #<Person:0x00005594bb47adb0 @name="Lisa">)
- What does the following code output?
class Animal
def speak
"I am an animal"
end
end
class Cow < Animal
def speak
"Moo"
end
end
Cow.new.speak
Answer
"Moo"
- What is the term for what is happening here?
class Animal
def speak
"I am an animal"
end
end
class Cow < Animal
def speak
"Moo"
end
end
Cow.new.speak
Answer
Method overriding
- Which of the following modifications would cause the code to output
100
? Mark all that apply.
class BankAccount
attr_reader :amount
def initialize(amount)
@amount
end
end
new_account = BankAccount.new(10)
new_account.amount = 100
puts new_account.amount
- A. No modification is needed.
- B. Change
attr_reader
toattr_writer
- C. Change
attr_reader
toattr_accessor
- D. Add
attr_writer :amount
- E. Define a method
def amount(value); @amount = value; end
- F. Define a method
def amount=(value); @amount = value; end
Answer
C, D, F
- What does the following code output?
class LivingThing
end
class Plant < LivingThing
end
class Animal < LivingThing
end
class Dog < Animal
end
class Cat < Animal
end
class Bengal < Cat
end
p Bengal.ancestors
Answer
[Bengal, Cat, Animal, LivingThing, Object, Kernel, BasicObject]
- What does the following code output?
class LivingThing
end
class Plant < LivingThing
end
class Animal < LivingThing
end
class Dog < Animal
end
class Cat < Animal
end
class Bengal < Cat
end
p Plant.ancestors
Answer
[Plant, LivingThing, Object, Kernel, BasicObject]
- What does the following code output?
class Cat
def initialize(name)
@name = name
end
end
gemma = Cat.new("Gemma")
puts gemma
- A.
"Gemma"
- B.
NoMethodError
- C. A string representation of the calling object (e.g.,
#<Cat:0x0000561e68d77698>
)
Answer
C
- What does the following code output?
class Cat
def initialize(name)
@name = name
end
def to_s
@name
end
end
gemma = Cat.new("Gemma")
puts gemma
- A.
"Gemma"
- B.
NoMethodError
- C. A string representation of the calling object (e.g.,
#<Cat:0x0000561e68d77698>
)
Answer
A
- What does the following code output?
class Cat
def initialize(name)
@name = name
end
def to_s
@name
end
end
class Bengal < Cat
def to_s
"I am a Bengal and my name is #{@name}."
end
end
gemma = Bengal.new("Gemma")
puts gemma
- A.
"Gemma"
- B.
NoMethodError
- C. A string representation of the calling object (e.g.,
#<Cat:0x0000561e68d77698>
) - D.
"I am a Bengal and my name is #{@name}."
Answer
D
- What does the following code output?
class Cat
def initialize(name)
@name = name
end
end
gemma = Cat.new("Gemma")
rosie = Cat.new("Rosie")
def gemma.fly
"I can fly!"
end
puts gemma.fly
puts rosie.fly
Answer
"I can fly!"
NoMethodError (undefined method `fly' for #<Cat:0x00005594bb468160 @name="Rosie">)
- What does
self
refer to in the following code?
class Person
@@counter = 0
def initialize
@@counter += 1
end
def self.counter
@@counter
end
end
Answer
the Person
class
- What does
self
refer to in the following code?
class Person
def initialize(name)
@name = name
end
def my_method
self
end
end
Answer
the calling object (an instance of the Person
class)
- What does
self
refer to in the following code?
class Person
self
def initialize(name)
@name = name
end
end
Answer
the Person
class
- Which of the following modifications would cause the code to output
"I am breathing"
? Select all that apply.
module Breathable
def breathe
"I am breathing"
end
end
class Person
def initialize(name)
@name = name
end
end
erma = Person.new("Erma")
puts erma.breathe
- A. Add
include breathe
in the Person class - B. Add
mixin breathe
in the Person class - C. Add
prepend breathe
in the Person class - D. Add
append breathe
in the Person class - E. Add
include Breathable
in the Person class - F. Add
mixin Breathable
in the Person class - G. Add
prepend Breathable
in the Person class - H. Add
append Breathable
in the Person class
Answer
E, G
- What does the following code output?
module LandMovements
def walk; end
def run; end
end
module WaterMovements
def swim; end
def splash; end
end
module SkyMovements
def fly; end
def soar; end
end
module Consume
def eat; end
def drink; end
end
class Animal
include Consume
end
class Duck < Animal
include LandMovements
include WaterMovements
include SkyMovements
end
p Duck.ancestors
Answer
[Duck, SkyMovements, WaterMovements, LandMovements, Animal, Consume, Object, Kernel, BasicObject]
- What does the following code output?
module M
def my_method
"Method inside module"
end
end
class C
include M
def my_method
"Method inside class"
end
end
puts C.new.my_method
Answer
"Method inside class"
- What does
self
refer to in the following code?
module M
def my_method
self
end
end
Answer
the calling object (the object that belongs to a class in which the module was mixed in)
- True or False: You can instantiate objects from modules.
Answer
False
- True or False: You can instantiate objects from classes.
Answer
True
- What does the following code output?
class Person
attr_reader :name
def initialize(name)
@name = name
end
end
class Student < Person
def initialize(name)
@occupation = "Student"
end
end
beatrice = Student.new("Beatrice")
puts beatrice.name
Answer
nil
- Which of the following lines of code, when used to replace
[CODE GOES HERE]
in the snippet below, would cause the program to output "Beatrice", when run? Select all that apply.
class Person
attr_reader :name
def initialize(name)
@name = name
end
end
class Student < Person
def initialize(name, major)
[CODE GOES HERE]
@major = major
@occupation = "Student"
end
end
beatrice = Student.new("Beatrice", "Computer Science")
puts beatrice.name
- A.
super
- B.
super(name)
- C.
super(name, major)
- D.
super(major)
Answer
B
- Does an instance of the
Bengal
class have access to theexcrete
method defined in the moduleBiologicalFunctions
?
module BiologicalFunctions
def eat; end
def sleep; end
def excrete; end
end
class Animal
include BiologicalFunctions
end
class Cat < Animal
end
class Bengal < Cat
end
Answer
Yes
- Which of the following are valid ways to access the
NUM_ITEMS
constant in classAbc
?
class Abc
NUM_ITEMS = 2
end
- A.
Abc.NUM_ITEMS
- B.
Abc[NUM_ITEMS]
- C.
Abc:NUM_ITEMS
- D.
Abc::NUM_ITEMS
- E.
Abc||NUM_ITEMS
Answer
D
- What does the following code output?
class Abc
NUM_ITEMS = 2
end
class SubAbc < Abc
end
instance = SubAbc.new
puts instance::NUM_ITEMS
Answer
TypeError (#<SubAbc:0x000055bbbb4f0ef8> is not a class/module)
- What does the following code output?
class Abc
NUM_ITEMS = 2
end
class SubAbc < Abc
end
instance = SubAbc.new
puts instance.class::NUM_ITEMS
Answer
2
- What does the following code output?
class Abc
NUM_ITEMS = 2
end
class SubAbc < Abc
NUM_ITEMS = 4
end
instance = SubAbc.new
puts instance.class::NUM_ITEMS
Answer
4
- What does the following code output?
class Abc
NUM_ITEMS = 2
end
class SubAbc < Abc
def message
"I have #{NUM_ITEMS} items."
end
end
instance = SubAbc.new
puts instance.message
Answer
"I have 2 items"
- What does the following code output?
module MyModule
def message
"I have #{NUM_ITEMS} items."
end
end
class Abc
NUM_ITEMS = 2
end
class SubAbc < Abc
include MyModule
end
instance = SubAbc.new
puts instance.message
Answer
NameError (uninitialized constant MyModule::NUM_ITEMS)
- What does the following code output?
module MyModule
def message
"I have #{self.class::NUM_ITEMS} items."
end
end
class Abc
NUM_ITEMS = 2
end
class SubAbc < Abc
include MyModule
end
instance = SubAbc.new
puts instance.message
Answer
"I have 2 items."
- What does the following code output?
module MyModule
def message
"I have #{self.class::NUM_ITEMS} items."
end
end
class Abc
include MyModule
NUM_ITEMS = 2
end
class SubAbc < Abc
NUM_ITEMS = 4
end
puts Abc.new.message
puts SubAbc.new.message
Answer
"I have 2 items."
"I have 4 items."
- Methods in a class are _______ by default.
- A. public
- B. private
- C. protected
Answer
A
- Getter methods in a class are _______ by default.
- A. public
- B. private
- C. protected
Answer
A
- Setter methods in a class are _______ by default.
- A. public
- B. private
- C. protected
Answer
A
- Given the following code, which of the following statements would run without error if placed in the code snippet area? Select all that apply.
class Person
attr_reader :age
def initialize(age)
@age = age
end
private
attr_writer :age
end
jane = Person.new(10)
[CODE SNIPPET HERE]
- A.
puts jane.age
- B.
jane.age = 20
- C.
jane.age += 1
- D.
jane.age > Person.new(5).age
Answer
A, D
- Given the following code, which of the following statements would run without error if placed in the code snippet area? Select all that apply.
class Person
def initialize(age)
@age = age
end
def ==(other)
age == other.age
end
protected
attr_reader :age
end
jane = Person.new(10)
[CODE SNIPPET HERE]
- A.
puts jane.age
- B.
jane.age = 20
- C.
jane.age == Person.new(5).age
- D.
jane == Person.new(5)
Answer
D
- Given the following code, which of the following statements, when placed in the code snippet area, would cause the puts statement to output 100? Select all that apply.
class Person
attr_reader :age
def initialize(age)
@age = age
end
def centenarian
[CODE SNIPPET HERE]
end
private
attr_writer :age
end
jane = Person.new(10)
jane.centenarian
puts jane.age
- A.
age = 100
- B.
self.age = 100
- C.
@age = 100
- D.
@self.age = 100
Answer
B, C
- Given the following code, which of the following statements, when placed in the code snippet area, would cause the puts statement to output 100? Select all that apply.
class Person
attr_reader :age
def initialize(age)
@age = age
end
def centenarian
[CODE SNIPPET HERE]
end
protected
attr_writer :age
end
jane = Person.new(10)
jane.centenarian
puts jane.age
- A.
age = 100
- B.
self.age = 100
- C.
@age = 100
- D.
@self.age = 100
Answer
B, C
- Given the following code, which of the following statements, when placed in the code snippet area, would cause the puts statement to output 100? Select all that apply.
class Person
attr_reader :age
def initialize(age)
@age = age
end
def centenarian
[CODE SNIPPET HERE]
end
public
attr_writer :age
end
jane = Person.new(10)
jane.centenarian
puts jane.age
- A.
age = 100
- B.
self.age = 100
- C.
@age = 100
- D.
@self.age = 100
Answer
B, C
- True or False: In the previous question, the use of the
public
keyword is unnecessary.
Answer
True
- Which of the following are valid ways to call the private setter method
secret=
, from withinmy_method
in the code below?
class Person
def my_method
[CODE SNIPPET HERE]
end
def secret=(message)
@secret = message
end
private :secret
end
- A.
secret = "ABC"
- B.
self.secret = "ABC"
- C.
variable = self; variable.secret = "ABC"
- D.
self.class.secret = "ABC"
Answer
B
- True or False: Subclasses inherit the method-access rules of their superclasses, by default. In other words, given a class C with a set of access rules, and a class D that is a subclass of C, instances of D exhibit the same access behavior as instances of C.
Answer
True
- True or False: Subclasses inherit the method-access rules of their superclasses. Even if you set up new access rules inside the child class, the new rules will be overridden by the access rules of its parent class.
Answer
False
- You can call a ______ method on an object
x
, if the default object (self
) is an instance of the same class asx
or of an ancestor or descendant class ofx
's class.
Answer
protected
- ______ methods can be called with an explicit receiver outside of the class.
Answer
public
- True or False: Class methods can be made private, protected, or public.
Answer
False
- What is the one exception to calling a private method with an explicit receiver?
Answer
Setter methods, only when the receiver is self
- True or False: A private method is the same as a singleton method (a method defined on an instance of a class).
Answer
False
- True or False: You can make singleton methods private, protected, or public.
Answer
True
- Which of the following code snippets outputs "Hello", given
n = 2
? Select all that apply.
- A.
if n > 1 puts "Hello" else puts "World" end
- B.
if n > 1 then puts "Hello" end
- C.
if n > 1; puts "Hello"; end
- D.
if n > 1 puts "Hello"
- E.
puts "Hello" if n > 1
- F.
puts "Hello" if n > 1 end
Answer
A, B, C, E
- Which of the following code snippets outputs "Hello", given
n = 100
? Select all that apply.
- A.
unless n < 1 puts "Hello" end
- B.
puts "Hello" unless n < 1
- C.
puts "Hello" unless n < 1 end
- D.
unless n < 1 puts "Hello"
- E.
unless n < 1; puts "Hello"; end
Answer
A, B, E
- What does this statement evaluate to?
x = 10
if x == 2
"a"
elsif x == 3
"b"
elsif x == 10
"c"
end
Answer
"c"
- What does this statement evaluate to?
x = 10
if x == 2
"a"
elsif x == 3
"b"
else
"c"
end
Answer
"c"
- What does this statement evaluate to?
x = 10
if x == 2
"a"
elsif x == 10
"b"
else
"c"
end
Answer
"b"
- What does this statement evaluate to?
x = 10
if x == 2
"a"
elsif x == 3
"b"
end
Answer
nil
- What does this code output?
if false
x = 1
end
p x
Answer
nil
- What does this code output?
if false
x = 1
end
p y
Answer
NameError (undefined local variable or method 'y' for main:Object)
- What does this code output?
if (x = 2)
puts "Hello"
else
puts "World"
end
Answer
"Hello"
- What does this code output?
answer = 'yes'
case answer
when 'yes'
puts 'Hello'
when 'no'
puts 'Goodbye'
when 'maybe'
puts 'OK I will wait'
else
puts 'I did not understand that'
end
Answer
"Hello"
- What does this code output?
answer = 'maybe'
case answer
when 'yes'
puts 'Hello'
when 'no'
puts 'Goodbye'
when 'maybe'
puts 'OK I will wait'
else
puts 'I did not understand that'
end
Answer
"OK I will wait"
- What method is called on an object in a case statement?
Answer
the threequal operator ===
, also known as the case equality method
- Which of the following is equivalent to this code snippet? Select all that apply. Hint: Think of obj1 as a range, and obj2 and obj3 as integers.
case obj1
when obj2
1
when obj3
2
end
- A.
if obj1 == obj2 1 elsif obj1 == obj3 2 end
- B.
if obj2 == obj1 1 elsif obj3 == obj1 2 end
- C.
if obj2 === obj1 1 elsif obj3 === obj1 2 end
- D.
if obj1 === obj2 1 elsif obj1 === obj3 2 end
Answer
C
- True or False:
obj1 === obj2
is equivalent toobj2 === obj1
, for all objects
Answer
False
- True or False:
obj1 === obj2
is equivalent toobj1.===(obj2)
, for all objects
Answer
True
- True or False:
obj1 === obj2
is equivalent toobj1 == obj2
, for all objects
Answer
False
- What is the output from the following code?
x = 10
puts case
when x == 1
'a'
when x < 0
'b'
when x > 0
'c'
when x < 100
'd'
else
'e'
end
Answer
"c"
- Which of the following are valid statements to output "Looping forever", forever? Select all that apply.
- A.
loop puts "Looping forever"
- B.
loop puts "Looping forever" end
- C.
loop do puts "Looping forever" end
- D.
loop do puts "Looping forever" end
- E.
loop do { puts "Looping forever" } end
- F.
loop { puts "Looping forever" } end
- G.
loop { puts "Looping forever" }
Answer
D, G
- What is the last number output in the following code?
x = 1
loop do
puts x
x += 1
break if x > 5
end
Answer
5
- What is the last number output in the following code?
x = 1
loop do
break if x > 5
puts x
x += 1
end
Answer
5
- What is the last number output in the following code?
x = 1
loop do
x += 1
puts x
break if x > 5
end
Answer
6
- What is the last number output in the following code?
x = 1
loop do
puts x
x += 1
next unless x == 10
break
end
Answer
9
- What is the last number output in the following code?
x = 1
loop do
x += 1
next unless x == 10
puts x
break
end
Answer
10
- Which of the following statements outputs the numbers 1 through 10, given
n = 1
? Select all that apply.
- A.
while n < 10 puts n end
- B.
until n > 10 puts n n += 1 end
- C.
loop do puts n n += 1 break if n == 10 end
- D.
begin puts n n += 1 end while n <= 10
Answer
B, D
- True or False: You must explicitly use the keywords
do
andend
when defining a do..end block forwhile
anduntil
and not using curly braces.
Answer
False
- True or False: You must explicitly use the keywords
do
andend
when defining a do..end block forloop
and not using curly braces.
Answer
True
- True or False: The method
my_loop
as defined below has the same behavior asloop
, as demonstrated by the last two statements below.
def my_loop
yield while true
end
my_loop { puts "Looping forever" }
loop { puts "Looping forever" }
Answer
True
- An iterator is a Ruby method that expects you to provide it with a ______ _______.
Answer
code block
- Control passes to the _______ when an iterator yields.
Answer
code block
- An iterator is called within a program ABC. The iterator runs and yields to a code block. The code within the code block runs and the code block is finished executing. What happens afterwards?
- A. Yielding to a code block is the same as returning from a method. Control passes to the program ABC.
- B. Control remains with the code block and the entire code block executes again and again, forever.
- C. Control passes to the method at the statement immediately following the call to yield.
Answer
C
- True or False: According to the Well-Grounded Rubyist, code blocks and method arguments are separate constructs. Code blocks are part of the method call syntax.
Answer
True
- True or False: You can always provide a method with a code block, even if the method does not do anything with it.
Answer
True
- True or False: If you provide any method with a code block, that method will yield.
Answer
False
- What does the following code output?
def my_method(array)
ctr = 0
acc = []
until ctr == array.size
yield array[ctr]
ctr += 1
end
end
my_method([1, 2, 3, 4, 5]) { |x| puts x + 1 }
Answer
2
3
4
5
6
- What does the following code output?
def my_method(array)
acc = []
array.each { |x| acc << yield x }
acc
end
p my_method([1, 2, 3, 4, 5]) { |x| x * 2 }
Answer
[2, 4, 6, 8, 10]
- What does the following code output?
def my_method(integer)
ctr = 0
while ctr < integer
yield ctr
ctr += 1
end
end
my_method(3) do |x|
puts x * 5
end
Answer
0
5
10
- What does the following code output?
def my_method(array)
acc = []
array.each { |x| acc << x if yield x }
acc
end
result = my_method([2, 5, 6, 9, 10]) { |x| x % 2 == 0 }
p result
Answer
[2, 6, 10]
- Is an exception a method or an object?
Answer
Object. An exception is an instance of the class Exception
or a descendant of that class.
- True or False: When an exception is raised, the program is ALWAYS aborted unless you have provided a
rescue
clause.
Answer
True
- Which of the following is the default exception raised by the
raise
method?
- A.
IOError
- B.
TypeError
- C.
StandardError
- D.
RuntimeError
Answer
D
- True or False:
NameError
,NoMethodError
, andTypeError
are all classes descended fromException
.
Answer
True
- Which of the following exceptions are raised when you pass 5 arguments to a method that accepts 2?
- A.
StandardError
- B.
RuntimeError
- C.
ArgumentError
- D.
TypeError
Answer
C
- Which of the following exceptions are raised by the default
method_missing
?
- A.
StandardError
- B.
NoMethodError
- C.
ArgumentError
- D.
TypeError
Answer
B
- What exceptions does the following code rescue?
n = gets.to_i
begin
result = 100 / n
rescue
puts "You cannot divide by zero."
end
puts "Your result is #{result}."
- A.
ZeroDivisionError
only. - B.
NameError
only. - C. Any exception that is a descendant class of
StandardError
. - D.
RuntimeError
only.
Answer
C
- True or False: If you use the
rescue
keyword inside a method or code block, you do not have to usebegin
explicitly, if you want therescue
clause to apply to the entire method or block.
Answer
True
- What happens if you have the following code,
raise "Problem!"
- A. A
StandardError
is raised, and the message"Problem!"
is returned. - B. A
RuntimeError
is raised, and the message"Problem!"
is returned. - C. A
GenericError
is raised, and the message"Problem!"
is returned. - D. This is improper syntax. You must specify the exception to raise.
Answer
B
- How would you write a
rescue
statement to rescue anArgumentError
and assign the exception object to the variablee
?
begin
# some code
[YOUR CODE HERE]
# some code
end
Answer
rescue ArgumentError => e
- When is an
ensure
clause executed? Select all that apply.
begin
# some code
rescue ArgumentError
# some code
ensure
# some code
end
- A. When an exception is raised and caught by the
rescue
statement - B. When an exception is raised and NOT caught by the
rescue
statement - C. When an exception is NOT raised
- D.
ensure
clauses do not exist in Ruby.
Answer
A, B, C
- Suppose you created an exception
MyCustomError
as follows. How would you write code to raise the exception when the arraymy_array
does not include the number2
?
module MyModule
class MyCustomError < StandardError; end
end
def some_method
# some code
[YOUR CODE HERE]
end
Answer
raise MyModule::MyCustomError unless my_array.include?(2)
- How can you create a new exception class? Select all that apply.
- A. Inherit from
Exception
. - B. Inherit from any descendant class of
Exception
.
Answer
A, B
- True or False:
RuntimeError
is a descendant ofStandardError
.
Answer
True
- Use two different literal constructors to instantiate a
String
object with value "hello".
Answer
"hello"
'hello'
- Use a literal constructor to instantiate a
Symbol
with namehello
.
Answer
:hello
- Use a literal constructor to instantiate an
Array
with values 1, 2, and 3.
Answer
[1, 2, 3]
- Use a literal constructor to instantiate a
Hash
with key:value pairs ("New York"
,"NY"
) and ("Los Angeles"
,"CA"
).
Answer
{"New York" => "NY", "Los Angeles" => "CA"}
- Use a literal constructor to instantiate a
Hash
with key:value pairs (:abc
,1
), (:def
,2
). Do this in two ways.
Answer
{:abc => 1, :def => 2}
{abc: 1, abc: 2}
- Which of the following statements are true of the range
(0..9)
? Select all that apply.
- A. Includes 0
- B. Includes 1
- C. Includes 8
- D. Includes 9
- E. Includes 10
Answer
A, B, C, D
- Which of the following statements are true of the range
(0...9)
? Select all that apply.
- A. Includes 0
- B. Includes 1
- C. Includes 8
- D. Includes 9
- E. Includes 10
Answer
A, B, C
- What is the term for things Ruby lets you do to make your code look nicer? (e.g.,
arr[0] = 3
instead ofarr.[]=(0, 3)
)
Answer
syntactic sugar
- Which of the following are methods instead of operators?
- A.
+
- B.
>
- C.
==
- D.
&&
- E.
===
- F.
[]
- G.
%
Answer
A, B, C, E, F, G
- True or False: All methods that end in
!
modify their receiver.
Answer
False
- True or False: It is considered best practice to only have a bang(
!
) method when you also have a non-bang equivalent.
Answer
True
- True or False:
true
andfalse
are objects.
Answer
True
- True or False:
true
is the only instance ofTrueClass
, andfalse
is the only instance ofFalseClass
Answer
True
- What is the Boolean value of
nil
?
Answer
false
- What is the Boolean value of
puts "text"
?
Answer
false
- What is the Boolean value of
def x; end
?
Answer
true
- What is the Boolean value of
class C; end
?
Answer
false
- What is the Boolean value of
class C; 1; end
?
Answer
true
- What is the Boolean value of
x = 10
?
Answer
true
- What does the
==
method do, when used to compare two instances of classObject
?
Answer
Returns true
if their object_id
s are identical; false
otherwise.
Ruby Docs:
==
is typically overridden in descendant classes to provide class-specific meaning.
- What does the
eql?
method do, when used to compare two instances of classObject
?
Answer
Returns true
if their object_id
s are identical; false
otherwise.
Ruby Docs:
The eql?
method returns true
if the two objects refer to the same hash key. This is used by Hash
to test members for equality. For objects of class Object
, eql?
is synonymous with ==
. Subclasses normally continue this tradition by aliasing eql?
to their overridden ==
method, but there are exceptions.
- What does the
equal?
method do, when used to compare two instances of classObject
?
Answer
Returns true
if their object_id
s are identical; false
otherwise.
Ruby Docs:
Unlike ==
, the equal?
method should never be overridden by subclasses as it is used to determine object identity (that is, a.equal?(b)
if and only if a
is the same object as b
.
- What does the following code return?
str1 = "text"
str2 = "text"
str1 == str2
Answer
true
- True or False: If you define
==
in your class, objects of that class will automatically have the!=
method defined to be the inverse of==
.
Answer
true
- What class provides full comparison functionality in Ruby?
Answer
Comparable
- What is the method you need to define to get access to the full set of comparison methods in Ruby? Assume you have already mixed in the appropriate module.
Answer
<==>
(the spaceship method)
- Which of the following is true of the below code? Select all that apply.
text = <<EOM
Hello World.
My cat's name is Victor.
He likes fleece blankets.
EOM
- A.
text
is a string. - B.
text
is a multiline string. - C.
text
is a "here" document, or here-doc. - D. If we inspected
text
, we would see "Hello World.\nMy cat's name is Victor.\nHe likes fleece blankets.\n" - E.
EOM
can be replaced with any delimiter.
Answer
A, B, C, D, E
- What does the following code return?
str = "pizza"
str[2]
Answer
"z"
- What does the following code return?
str = "pizza"
str[2, 3]
Answer
"zza"
- What does the following code return?
str = "The Wandering Earth"
str[1..6]
Answer
"he Wan"
- What does the following code output?
str = "The Wandering Earth"
str[1..2] = 'en'
puts str
Answer
"Ten Wandering Earth"
- What does the following code output?
str = "I want peppers and mushrooms on my pizza."
str.slice!("and mushrooms ")
puts str
Answer
"I want peppers on my pizza."
- What does the following code output?
str = "I want peppers and mushrooms on my pizza."
str["mushrooms"] = "pineapple"
puts str
Answer
"I want peppers and pineapple on my pizza."
- What does the following code return?
str = "1234567890"
str[-4..-1]
Answer
"7890"
- Which of the following returns "Cheese Pizza" but does not modify the receiver? Select all that apply. Assume
str = "Cheese"
.
- A.
str + " Pizza"
- B.
str << " Pizza"
- C.
str.append( "Pizza")
- D.
str.join( "Pizza")
Answer
A
- Which of the following causes an error to be thrown? Select all that apply. Assume
str = "Cheese"
.
- A.
str + " Pizza"
- B.
str << " Pizza"
- C.
str.append( "Pizza")
- D.
str.join( "Pizza")
Answer
C, D
- How are two strings of the same length sorted? (e.g.,
"basic" <=> "pizza"
)
Answer
Character by character, according to each character's ordinal code. The default encoding is UTF-8.
- How are two strings of different length sorted? (e.g.,
"basic" <=> "basics"
)
Answer
Character by character, according to each character's ordinal code. The default encoding is UTF-8.
If the strings are equal compared up to the length of the shorter one, then the longer string is considered greater than the shorter one.
- What does the following code return?
"I want pizza".upcase
Answer
"I WANT PIZZA"
- What does the following code return?
"Mr. Bird".downcase
Answer
"mr. bird"
- What does the following code return?
"Mr. Bird".swapcase
Answer
"mR. bIRD"
- What does the following code return?
"hello world".capitalize
Answer
"Hello world"
- What does the following code return?
"hello".rjust(10)
Answer
" hello"
(5 spaces + "hello"
)
- What does the following code return?
"hello".ljust(10)
Answer
"hello "
("hello" + 5 spaces)
- What does the following code return?
"hello".center(9)
Answer
" hello "
(2 spaces + "hello" + 2 spaces)
- What does the following code return?
"hello".center(9, '<>')
Answer
"<>hello<>"
- Which of the following returns "sunny day"? Select all that apply.
- A.
"sunny day\n".chop
- B.
"sunny day\n".chomp
- C.
"sunny day".chop
- D.
"sunny day".chomp
- E.
"sunny days are nice".chop("s are nice")
- F.
"sunny days are nice".chomp("s are nice")
Answer
A, B, D, F
- True or False: Symbols are immutable. You cannot alter a given symbol.
Answer
True
- True or False: When you see
:abc
in two places in the code, they refer to the same object.
Answer
True
- True or False: You can create a new symbol by using the literal constructor (e.g.,
:abc
) or calling thenew
method (e.g.,Symbol.new(abc)
)
Answer
False. You can only use the literal.
The Well-Grounded Rubyist page 238:
Because symbols are unique, there's no point having a constructor for them; Ruby has no
Symbol.new
method. You can't create a symbol any more than you can create a new integer. In both cases, you can only refer to them."
- True or False: When you define a method, the method definition returns its name as a symbol. (e.g.,
def abc; end
returns:abc
)
Answer
True
- True or False: If you use an identifier for two purposes, for example, as a local variable and also as a method name, the symbol appears twice in the symbol table.
Answer
False
The Well-Grounded Rubyist page 239-240:
The symbol table is just that: a symbol table.
Ruby keeps track of what symbols it's supposed to know about so it can look them up quickly. The inclusion of a symbol in the symbol table doesn't tell you anything about what the symbol is for.
- Create an Array with elements 1, 2, 3, 4, 5 using the
Array.new
method.
Answer
Array.new([1, 2, 3, 4, 5])
- Create an Array with elements 1, 2, 3, 4, 5 using the literal array constructor.
Answer
[1, 2, 3, 4, 5]
- What does the following code return?
Array.new(2)
Answer
[nil, nil]
- What does the following code return?
Array.new(3, "hello")
Answer
["hello", "hello", "hello"]
- What does the following code return?
n = 0; Array.new(3) {n += 2; "#{n} dogs"}
Answer
["2 dogs", "4 dogs", "6 dogs"]
- When you run
Array.new(3, "hello")
are the resulting objects in the Array the same object, or different objects?
Answer
same object
- When you run
Array.new(3) {"hello"}
are the resulting objects in the Array the same object, or different objects?
Answer
different objects
- What does the following code return?
[1, 2, 3][1]
Answer
2
- What does the following code return?
%w{ Did you get that? }
Answer
["Did", "you", "get", "that?"]
- What does the following code return?
%w{ orange\ juice carrots oatmeal }
Answer
["orange juice", "carrots", "oatmeal"]
- What does the following code return?
%w{ The cost is $#{5 + 10} }
Answer
["The", "cost", "is", "$\#{5", "+", "10}"]
- What does the following code return?
%W{ The cost is $#{5 + 10} }
Answer
["The", "cost", "is", "$15"]
- What is the difference between the %w and %W constructor?
Answer
%w
parses the strings in the list as single-quoted strings.
%W
parses the strings in the list as double-quoted strings.
- What does the following code return?
%i{ a b c }
Answer
[:a, :b, :c]
- What does the following code return?
%I{ #{"ab" + "cd"} }
Answer
[:abcd]
- What is the difference between the %i and %I constructor?
Answer
%i
parses the strings in the list as single-quoted strings.
%I
parses the strings in the list as double-quoted strings.
- What does the following code return?
%w{ a b c d e f }[2, 3]
Answer
["c", "d", "e"]
- What does the following code return?
%w{ a b c d e f }[5, 2]
Answer
["f"]
- What does the following code return?
%w{ a b c d e f }[-3, 3]
Answer
["d", "e", "f"]
- What does the following code return?
%w{ a b c d e f }[0..3]
Answer
["a", "b", "c", "d"]
- What does the following code return?
%w{ a b c d e f }[4..-1]
Answer
["e", "f"]
- What does the following code output?
arr = ["eagle", 10, :d, "hello world"]
arr[2] = "beast"
p arr
Answer
["eagle", 10, "beast", "hello world"]
- What does the following code return?
arr = ["eagle", 10, :d, "hello world"]
arr[3, 2] = [20, 30]
p arr
Answer
arr = ["eagle", 10, :d, 20, 30]
- What does the following code output?
arr = ["eagle", 10, :d, "hello world"]
def alter_table(array)
array[3, 2] = [20, 30]
end
alter_table(arr)
p arr
Answer
arr = ["eagle", 10, :d, 20, 30]
- What method can you use to insert an object at the beginning of an array?
Answer
unshift
- What method can you use to remove the object at the beginning of an array?
Answer
shift
- What methods can you use to insert an object at the end of an array? Name two.
Answer
push
, <<
, append
- What method can you use to remove the last object from an array?
Answer
pop
- What does the following code return?
[1, 2, 3].push([4, 5, 6])
Answer
[1, 2, 3, [4, 5, 6]]
- What does the following code return?
[1, 2, 3].concat([4, 5, 6])
Answer
[1, 2, 3, 4, 5, 6]
- Which of the following statements is true of the code below? Select all that apply.
a = [1, 2, 3]
b = [4, 5, 6]
a.concat(b)
- A.
a
is modified. - B.
b
is modified. - C. Neither
a
orb
are modified. A new object is created and returned.
Answer
A
- Which of the following statements is true of the code below? Select all that apply.
a = [1, 2, 3]
b = [4, 5, 6]
a + b
- A.
a
is modified. - B.
b
is modified. - C. Neither
a
orb
are modified. A new object is created and returned.
Answer
C
- What does the following code return?
[1, 2, 3].reverse
Answer
[3, 2, 1]
- What does the following code return?
[1, 2, [3], [4, [5, [6]]]].flatten
Answer
[1, 2, 3, 4, 5, 6]
- What does the following code return?
[1, 2, [3], [4, [5, [6]]]].flatten(1)
Answer
[1, 2, 3, 4, [5, [6]]]
- What does the following code return?
[1, 2, [3], [4, [5, [6]]]].flatten(2)
Answer
[1, 2, 3, 4, 5, [6]]
- What does the following code return?
["pizza", :abc, 33].join
Answer
"pizzaabc33"
- What does the following code return?
["pizza", :abc, 33].join(", ")
Answer
"pizza, abc, 33"
- What does the following code return?
["pizza", :abc, 33] * "-"
Answer
"pizza-abc-33"
- What does the following code return?
[3, 4, 4, 5, 5, 4, 3].uniq
Answer
[3, 4, 5]
- What
Array
method can you use to return a new array identical to the original array, with all occurrences ofnil
removed? e.g.,[12, 3, nil, 4, nil].method => [12, 3, 4]
Answer
compact
- What Array method can you use to return the number of elements in the array?
Answer
size
or length
- What
Array
method can you use to returntrue
if the caller is an empty array andfalse
otherwise?
Answer
empty?
- What
Array
method can you use to returntrue
if the array includes at least one occurrence of the item, andfalse
otherwise? e.g.,[1, 2, 3].method(2) => true
Answer
include?
- What
Array
method can you use to return the number of occurrences of the item in the array? e.g.,[1, 2, 3, 4, 4].method(4) => 2
Answer
count
- What
Array
method can you use to return the first n items in the array?
Answer
take
or first
- What
Array
method can you use to return the last n items in the array?
Answer
last
- What
Array
method can you use to return n random elements from the array, where the maximum number of elements returned is equal to the number of items in the array (sampling without replacement)?
Answer
sample
- Create an empty hash using the literal constructor.
Answer
{}
- Create an empty hash with default values of 0 using the
Hash.new
method.
Answer
Hash.new(0)
- Create a hash with key and value pairs (
"one"
,"a"
), ("two"
,"b"
) using theHash.[]
method.
Answer
Hash["one", "a", "two", "b"]
or Hash[[["one", "a"], ["two", "b"]]]
- Create a hash with key and value pairs (
:a
:12
), (:b
,30
) using the literal constructor and hash rockets. (=>
)
Answer
{:a => 12, :b => 30}
- Create a hash with key and value pairs (
:a
:12
), (:b
,30
) using the literal constructor and the syntactical sugar for symbol keys.
Answer
{a: 12, b: 30}
- Suppose you have an empty hash
sounds
. Add the key and value pair (:cow, "moo") to thesounds
hash using the[]=
method and syntactical sugar.
Answer
sounds[:cow] = "moo"
- Suppose you have an empty hash
sounds
. Add the key and value pair (:cow, "moo") to thesounds
hash using thestore
method.
Answer
sounds.store(:cow, "moo")
- Which of the following are required to be unique in hashes? Select all that apply.
- A. keys
- B. values
- C. neither
Answer
A
- What does the following code output?
hash = {"Jake" => "octopus", "Chandler" => "chicken"}
hash["Jake"] = "snake"
puts hash["Jake"]
Answer
"snake"
- What is returned from executing the following code?
hash = {"Jake" => "octopus", "Chandler" => "chicken"}
hash["Doreen"]
Answer
nil
- What is returned from executing the following code?
hash = {"Jake" => "octopus", "Chandler" => "chicken"}
hash.fetch("Doreen")
Answer
KeyError (key not found: "Doreen")
- What is returned from executing the following code?
hash = Hash.new("dog")
hash["Doreen"]
Answer
"dog"
- What is returned from executing the following code?
hash = Hash.new("dog")
hash.fetch("Doreen")
Answer
KeyError (key not found: "Doreen")
- What is returned from executing the following code?
hash = Hash.new("dog")
hash.fetch("Doreen", "monkey")
Answer
"monkey"
- How can you retrieve values for both "Grace" and "Frankie" in the following hash?
hash = {"Grace" => "salad", "Frankie" => "pancakes", "Sol" => "spinach"}
Use a method that would return the array["salad", "pancakes"]
.
Answer
hash.values_at("Grace", "Frankie")
- What does the following code output?
hash = Hash.new {|h,k| h[k] = 0}
hash[:a]
p hash
Answer
{:a => 0}
- Which of the following statements are true given the code below?
h1 = {"muffin" => 2.50,
"coffee" => 2.00}
h2 = {"sparkling water" => 1.80,
"coffee" => 3.20}
h1.update(h2)
- A. A new hash is returned containing the following key and value pairs:
{"muffin" => 2.50, "coffee" => 2.00, "sparkling water" => 1.80, "coffee" => 3.20}
- B. A new hash is returned containing the following key and value pairs:
{"muffin" => 2.50, "coffee" => 2.00, "sparkling water" => 1.80}
- C. A new hash is returned containing the following key and value pairs:
{"muffin" => 2.50, "coffee" => 3.20, "sparkling water" => 1.80}
- D. h1 is updated to contain the following key and value pairs:
{"muffin" => 2.50, "coffee" => 2.00, "sparkling water" => 1.80}
- E. h1 is updated to contain the following key and value pairs:
{"muffin" => 2.50, "coffee" => 3.20, "sparkling water" => 1.80}
- F. h2 is updated to contain the following key and value pairs:
{"muffin" => 2.50, "coffee" => 2.00, "sparkling water" => 1.80}
- G. h2 is updated to contain the following key and value pairs:
{"muffin" => 2.50, "coffee" => 3.20, "sparkling water" => 1.80}
Answer
E
- Which of the following statements are true given the code below?
h1 = {"muffin" => 2.50,
"coffee" => 2.00}
h2 = {"sparkling water" => 1.80,
"coffee" => 3.20}
h1.merge(h2)
- A. A new hash is returned containing the following key and value pairs:
{"muffin" => 2.50, "coffee" => 2.00, "sparkling water" => 1.80, "coffee" => 3.20}
- B. A new hash is returned containing the following key and value pairs:
{"muffin" => 2.50, "coffee" => 2.00, "sparkling water" => 1.80}
- C. A new hash is returned containing the following key and value pairs:
{"muffin" => 2.50, "coffee" => 3.20, "sparkling water" => 1.80}
- D. h1 is updated to contain the following key and value pairs:
{"muffin" => 2.50, "coffee" => 2.00, "sparkling water" => 1.80}
- E. h1 is updated to contain the following key and value pairs:
{"muffin" => 2.50, "coffee" => 3.20, "sparkling water" => 1.80}
- F. h2 is updated to contain the following key and value pairs:
{"muffin" => 2.50, "coffee" => 2.00, "sparkling water" => 1.80}
- G. h2 is updated to contain the following key and value pairs:
{"muffin" => 2.50, "coffee" => 3.20, "sparkling water" => 1.80}
Answer
C
- Given the hash
my_hash
, use theselect
method to return a new hash containing only those elements frommy_hash
where the value is greater than 10. Assume all values inmy_hash
are Integers.
Answer
my_hash.select {|_,v| v > 10}
- Given the hash
my_hash
, use thereject
method to return a new hash containing all of the elements frommy_hash
except those where the key is less than 100. Assume all keys inmy_hash
are Integers.
Answer
my_hash.reject {|k, _| k < 100}
- Name at least 2 methods that return true if the hash
h
includes the keyk
, as expressed in this usage:h.method(k)
Answer
has_key?
, key?
, include?
, member?
- Name at least 1 method that returns true if the hash
h
includes the valuev
, as expressed in this usage:h.method(v)
Answer
has_value?
, value?
- Use the literal constructor to create a range of the numbers
1
,2
,3
,4
,5
.
Answer
(1..5)
or (1...6)
- What is the difference between
1..10
and1...10
?
Answer
1..10
includes 10
.
1...10
does not.
- Which
Range
method returnstrue
if the argument to the method is greater than the range's start point and less than its end point (or equal to the end point, for an inclusive range)?
Answer
cover?
- Which
Range
method treats the range as a collection of values, and returnstrue
if the argument to the method is among the values in the collection?
Answer
include?
- Which of the following statements return
true
, givenr = "a".."z"
? Select all that apply.
- A.
r.cover?("k")
- B.
r.cover?("cat")
- C.
r.cover?("P")
- D. None of the above
Answer
A, B
- Which of the following statements return
true
, givenr = "a".."z"
? Select all that apply.
- A.
r.include?("k")
- B.
r.include?("cat")
- C.
r.include?("P")
- D. None of the above
Answer
A
- Which of the following statements return
true
, givenr = "z".."a"
? Select all that apply.
- A.
r.cover?("k")
- B.
r.cover?("cat")
- C.
r.cover?("P")
- D. None of the above
Answer
D
- Which of the following statements return
true
, givenr = "z".."a"
? Select all that apply.
- A.
r.include?("k")
- B.
r.include?("cat")
- C.
r.include?("P")
- D. None of the above
Answer
D
- Which of the following statements return
true
, givenr = 1..100
? Select all that apply.
- A.
r.cover?(3)
- B.
r.cover?(5.5)
- C. None of the above
Answer
A, B
- Which of the following statements return
true
, givenr = 1..100
? Select all that apply.
- A.
r.include?(3)
- B.
r.include?(5.5)
- C. None of the above
Answer
A
- Which of the following statements return
true
, givenr = 100..1
? Select all that apply.
- A.
r.cover?(3)
- B.
r.cover?(5.5)
- C. None of the above
Answer
C
- Which of the following statements return
true
, givenr = 100..1
? Select all that apply.
- A.
r.include?(3)
- B.
r.include?(5.5)
- C. None of the above
Answer
C
- What line of code do you need to include in your file to use the
Set
class? Why? For the rest of the set-related questions, assume that this line of code has been run.
Answer
require 'set'
, because Set
is a standard library class. If it was a core class, you would not need to do this.
- Create a set using the
Set.new
constructor, with the elements"banana"
,"bagel"
, and"lettuce"
.
Answer
Set.new(["banana", "bagel", "lettuce"])
- Is there a literal constructor for sets?
Answer
No, because sets are part of the standard library, not the core.
- Which of the following happens when you run the code below?
groceries = Set.new(["apple", "cheese", "milk"])
groceries << "cheese"
- A.
groceries
now contains only"apple"
and"milk"
. - B. You get an error.
- C. You get a warning.
- D.
groceries
still contains only"apple"
,"cheese"
, and"milk"
.
Answer
D
- Which of the following happens when you run the code below?
groceries = Set.new(["apple", "cheese", "milk"])
groceries << "scallions"
- A.
groceries
now contains"apple"
,"cheese"
,"milk"
, and"scallions"
. - B. You get an error.
- C. You get a warning.
- D.
groceries
still contains"apple"
,"cheese"
, and"milk"
.
Answer
A
- Which of the following happens when you run the code below?
groceries = Set.new(["apple", "cheese", "milk"])
groceries.delete("apple")
- A.
groceries
now contains only"cheese"
and"milk"
. - B. You get an error.
- C. You get a warning.
- D.
groceries
still contains"apple"
,"cheese"
, and"milk"
.
Answer
A
- Which of the following happens when you run the code below?
groceries = Set.new(["apple", "cheese", "milk"])
groceries.delete("bread")
- A. You get an error.
- B. You get a warning.
- C. Nothing happens.
groceries
still contains"apple", "cheese", "milk"
.
Answer
C
- What
Set
method is an alias for<<
?
Answer
add
- What is the difference between the Set methods
add
andadd?
?
Answer
If the set is unchanged after the operation, add
would return the set but add?
would return nil
.
- Suppose you have the sets
set_a
andset_b
. Write a statement that returns a new set containing only the elements that appear in bothset_a
andset_b
. Use aSet
method.
Answer
set_a & set_b
or set_a.intersection(set_b)
- Suppose you have the sets
set_a
andset_b
. Write a statement that returns a new set containing items that appear in eitherset_a
orset_b
, or both. Use aSet
method.
Answer
set_a | set_b
, set_a + set_b
, or set_a.union(set_b)
- Suppose you have the sets
set_a
andset_b
. Write a statement that returns all items in set_a that do not show up in in set_b. Use aSet
method.
Answer
set_a - set_b
or set_a.difference(set_b)
- Suppose you have the sets
set_a
andset_b
. Write a statement that returns the items that only show up in eitherset_a
orset_b
but not both. Use a Set method.
Answer
set_a ^ set_b
or (set_a | set_b) - (set_a & set_b)
- Which of the following statements would be true after the code below is run? Select all that apply.
lang_1 = Set.new(["Ruby", "Javascript"])
lang_2 = Set.new(["Python"])
lang_1.merge(lang_2)
- A. A new set is returned:
#<Set: {"Ruby", "Javascript", "Python"}>
- B.
lang_1
is updated to the following:#<Set: {"Ruby", "Javascript", "Python"}>
- C.
lang_2
is updated to the following:#<Set: {"Ruby", "Javascript", "Python"}>
- D. You get an error.
Answer
B
- Which of the following statements would return
true
given the code below?
library_books = Set.new(['The Poet X', "Meditations", "Oathbringer"])
my_books = Set.new(["Oathbringer", "Meditations"])
your_books = Set.new(['The Poet X', "Meditations", "Oathbringer"])
- A.
library_books.superset?(my_books)
- B.
library_books.superset?(your_books)
- C.
library_books.proper_superset?(my_books)
- D.
library_books.proper_superset?(your_books)
- E.
my_books.superset?(library_books)
- F.
my_books.superset?(your_books)
- G.
my_books.subset?(library_books)
- H.
my_books.proper_subset?(library_books)
- I.
your_books.proper_subset?(library_books)
Answer
A, B, C, G, H
There are multiple ways to answer some of these questions. Test your answers in irb if they differ from the given answers.
- What does the following code return?
/abc/.match("Hello abcdefg").class
Answer
MatchData
- What does the following code return?
"Hello abcdefg".match(/abc/).class
Answer
MatchData
- What does the following code return?
"Hello abcdefg".match(/123/)
Answer
nil
- What does the following code return?
/123/.match("Hello abcdefg")
Answer
nil
- What does the following code return?
/abc/ =~ "Alpha abc"
Answer
6
- True or False:
/abc/ =~ "Alpha abc"
is equivalent to"Alpha abc" =~ /abc/
Answer
True
- Some characters have special meanings to the regexp parser. When you want to match one of these special characters as itself. what do you have to do?
Answer
Escape it with the backslash character \
- What special character can you use to match any character, except newline?
Answer
The dot wildcard character .
- Use a character class to write a pattern that would match either
"t"
or"b"
, followed by"ees"
. In other words, it would match"tees"
and"bees"
, but not"sees"
.
Answer
/[tb]ees/
- True or False:
/[br]ead/ =~ "bread"
returnsnil
.
Answer
False
- Use a character class to write a pattern that would match any lowercase or uppercase letter.
Answer
/[a-z]/i
or [a-zA-Z]
or [A-Za-z]
- There exists special escape sequences for some common character sequences. What is the special escape sequence to match any digit?
Answer
\d
- What is the special escape sequence to match any digit, alphabetical character, or underscore?
Answer
\w
- What is the special escape sequence to match any whitespace character (space, tab, newline)?
Answer
\s
- What are the negated forms of the special character sequences to match (1) any digit, (2) any digit, alphabetical character, or underscore, and (3) any whitespace character (space, tab, newline)?
Answer
\D
, \W
, \S
- True or False: When using the special character sequences, you must enclose them in square brackets, as you would for a regular character class.
Answer
False
- Write a pattern that would capture the first name and last name from the following string: "Elizabeth Acevedo, eacevedo@email.com"
Answer
/([A-Za-z]+) ([A-Za-z]+)/
- Write a pattern that would capture the email address from the following string: "Elizabeth Acevedo, eacevedo@email.com"
Answer
/([a-z]+@[a-z]+\.[a-z]+)/
- Suppose you have a
MatchData
objectm
containing some captures. What are two ways you can access the third capture?
Answer
m[3]
or m.captures[2]
- Suppose you have a
MatchData
object containing some captures. WhatMatchData
method can you use to get the part of the string before the part that matched? WhatMatchData
method can you use to get the part of the string after the part that matched?
Answer
pre_match
; post_match
- True or False: All quantifiers operate either on a single character (which may be represented by a character class) or on a parenthetical group.
Answer
True
- Write a pattern that uses the zero-or-one quantifier to match either "hi", "his", but NOT "hiss".
Answer
/his?/
- Write a pattern that uses the zero-or-more quantifier to match either "hi", "his", "hiss", or "hissssssss".
Answer
/his*/
- Write a pattern that uses the one-or-more quantifier to match any sequence of one or more consecutive digits.
Answer
/\d+/
- Write a pattern that matches exactly 5 digits, followed by a hyphen(-), followed by exactly 4 digits.
Answer
/\d{5}-\d{4}/
- Write a pattern that matches 2 to 10 digits, followed by a hyphen(-), followed by 2 to 5 digits.
Answer
/\d{2,10}-\d{2,5}/
- Write a pattern that matches exactly 2 digits, followed by a hyphen(-), followed by 5 or more digits.
Answer
/\d{2}-\d{5,}/
- What is the anchor for beginning of line? What is the anchor for end of line?
Answer
^
; $
- What is the anchor for beginning of a string? What is the anchor for end of string (including the final newline)? What is the anchor for end of the string (NOT including the final newline)?
Answer
\A
, \z
, \Z
- What is the anchor for word boundary?
Answer
\b
- Write a pattern to match either "abc" or "ABC". Use the case-insensitive modifier.
Answer
/abc/i
- Which modifier has the effect that the wildcard dot character, which normally matches any character except newline, will match any character, including newline? This is useful when you want to capture everything between, for example, an opening and closing parenthesis, and you do not care whether they are on the same line.
Answer
the multi-line modifier m
- Which
String
method goes from left to right in a string, testing repeatedly for a match with the specified pattern, and returns the matches in array?
Answer
scan
- Create a
Proc
object by instantiating theProc
class with a code block{puts "Hello"}
.
Answer
Proc.new {puts "Hello"}
- True or False: When you create a
Proc
object, you must supply a code block.
Answer
True
- True or False: Every code block serves as the basis of a proc.
Answer
False
- True or False: A code block is an object.
Answer
False
- True or False: Procs can serve as code blocks.
Answer
True
- What does the
&
inmy_method(&p)
do?
def my_method(&block)
block.call
end
p = Proc.new {puts "Hello"}
my_method(&p)
Answer
&
triggers a call to p
's to_proc
method and tells Ruby that the resulting Proc
object is serving as a code block stand-in.
- Suppose you have an array of words,
words
. How would you use theSymbol#to_proc
method to return a new array where each word inwords
is capitalized?
Answer
words.map(&:capitalize)
- True or False:
array.map(&:to_i)
is equivalent toarray.map {|x| x.to_i}
Answer
True
- True or False:
array.map(&:to_i)
is equivalent toarray.map {|x| x.send(:to_i)}
Answer
True
- What is the term for a piece of code that carries its creation context around with it?
Answer
closure
- What does the following code output?
def make_counter
n = 0
return Proc.new { n+= 1 }
end
c = make_counter
puts c.call
d = make_counter
puts d.call
puts d.call
Answer
1
1
2
- True or False: Procs enforce argument count.
Answer
False
- True or False: The
lambda
method returns aProc
object.
Answer
True
- True or False: Lambdas enforce argument count.
Answer
True
- Is the following sentence true of a lambda or a proc?
return
inside a (lambda/proc) triggers an exit from the body of the (lambda/proc) to the context immediately containing the (lambda/proc).
Answer
lambda
- Is the following sentence true of a lambda or a proc?
return
inside a (lambda/proc) triggers a return from the method in which the (lambda/proc) is being executed.
Answer
proc
- Instantiate a lambda using the
lambda
method, with a code block{ puts "Hi" }
.
Answer
lambda {puts "Hi"}
- Instantiate a lambda using the "stabby lambda" literal constructor, with a code block
{ puts "Hi" }
.
Answer
-> {puts "Hi"}