Skip to content

Created 346 Ruby questions based on content from The Well-Grounded Rubyist

Notifications You must be signed in to change notification settings

nantrinh/ruby_practice_problems

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

52 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Ruby Practice Problems

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

Table of Contents

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

Ruby Basics

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


  1. Given name = "Frodo", write a puts statement that outputs "My dog is named Frodo." Use string interpolation.
Answer

puts "My dog is named #{name}."


  1. Create a symbol named abc using the literal constructor.
Answer

:abc


  1. What is returned from executing the following statement? 1 + 2
Answer

3


  1. What is returned from executing the following statement? 1 * 2
Answer

2


  1. What is returned from executing the following statement? 5 / 2
Answer

2


  1. What is returned from executing the following statement? 5 / 2.0
Answer

2.5


  1. What is returned from executing the following statement? 5.0 / 2.0
Answer

2.5


  1. What is returned from executing the following statement? 10 % 2
Answer

0


  1. What is returned from executing the following statement? 10 % 3
Answer

1


  1. What is output from executing the following statement? puts "Hello World"
Answer

"Hello World"


  1. What is returned from executing the following statement? puts "Hello World"
Answer

nil


  1. What is returned from executing the following statement? "Hello World".nil?
Answer

false


  1. What is returned from executing the following statement? 0.nil?
Answer

false


  1. What is returned from executing the following statement? "".nil?
Answer

false


  1. What is returned from executing the following statement? false.nil?
Answer

false


  1. Create an array using the literal constructor consisting of the elements "a", "b", and "c". Assign it to the local variable arr.
Answer

arr = ["a", "b", "c"]


  1. 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 variable integers.
Answer

integers = {"one" => 1, "two" => 2, "three" => 3}


  1. What is output from executing the following statement? puts [1, 2, 3]
Answer

1
2
3


  1. What is output from executing the following statement? puts [1, 2, 3].inspect
Answer

[1, 2, 3]


  1. What is output from executing the following statement? p [1, 2, 3]
Answer

[1, 2, 3]


  1. Write a statement that converts the integer 1 to its string representation.
Answer

1.to_s


  1. Write a statement that converts the string "1230" to its integer representation.
Answer

"1230".to_i


  1. What is returned from executing the following statement? "123.5".to_f
Answer

123.5


  1. What is returned from executing the following statement? "001230".to_i
Answer

1230


  1. What is returned from executing the following statement? "123ab23".to_i
Answer

123

Objects, Methods, and Local Variables

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


  1. What does the following code output?
a = 5

def my_method(a)
  puts a
end

my_method(10)
Answer

10


  1. What does the following code output?
a = 5

def my_method
  a = 20
  puts a
end

my_method
Answer

20


  1. What does the following code output?
str = "Hello World" 

def my_method(str)
  str = ''
end

my_method(str)
puts str
Answer

"Hello World"


  1. 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"


  1. What does the following code output?
str = "Hello World" 

def my_method(str)
  str.upcase!
end

my_method(str)
puts str
Answer

"HELLO WORLD"


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


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


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


  1. What does the following code output?
def my_method(*arg1)
  arg1
end

p my_method(1, 2, 3, 4)
Answer

[1, 2, 3, 4]


  1. What does the following code output?
def my_method(arg1=0, arg2=0)
  [arg1, arg2] 
end

p my_method(1)
Answer

[1, 0]


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


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


  1. What does the following code output?
a = 5

loop do
  puts a
  break
end
Answer

5


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


  1. 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"


  1. What does the following code output?
def my_method
  return "Hello Marian"
  "Hello Robin Hood"
end

p my_method
Answer

"Hello Marian"

Classes and self

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


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


  1. What kind of variable is @name?
Answer

instance variable


  1. What kind of variable is @@name?
Answer

class variable


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


  1. 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"


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


  1. 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 to attr_writer
  • C. Change attr_reader to attr_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


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


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


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


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


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


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


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


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


  1. What does self refer to in the following code?
class Person
  self

  def initialize(name)
    @name = name
  end
end
Answer

the Person class

Modules, super, and Constant Resolution

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


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


  1. 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"


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


  1. True or False: You can instantiate objects from modules.
Answer

False


  1. True or False: You can instantiate objects from classes.
Answer

True


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


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


  1. Does an instance of the Bengal class have access to the excrete method defined in the module BiologicalFunctions?
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


  1. Which of the following are valid ways to access the NUM_ITEMS constant in class Abc?
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


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


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


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


  1. 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"


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


  1. 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."


  1. 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."

Private and Protected Methods

  1. Methods in a class are _______ by default.
  • A. public
  • B. private
  • C. protected
Answer

A


  1. Getter methods in a class are _______ by default.
  • A. public
  • B. private
  • C. protected
Answer

A


  1. Setter methods in a class are _______ by default.
  • A. public
  • B. private
  • C. protected
Answer

A


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


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


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


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


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


  1. True or False: In the previous question, the use of the public keyword is unnecessary.
Answer

True


  1. Which of the following are valid ways to call the private setter method secret=, from within my_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


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


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


  1. You can call a ______ method on an object x, if the default object (self) is an instance of the same class as x or of an ancestor or descendant class of x's class.
Answer

protected


  1. ______ methods can be called with an explicit receiver outside of the class.
Answer

public


  1. True or False: Class methods can be made private, protected, or public.
Answer

False


  1. What is the one exception to calling a private method with an explicit receiver?
Answer

Setter methods, only when the receiver is self


  1. True or False: A private method is the same as a singleton method (a method defined on an instance of a class).
Answer

False


  1. True or False: You can make singleton methods private, protected, or public.
Answer

True

if, else, and case

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


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


  1. What does this statement evaluate to?
x = 10
if x == 2
  "a"
elsif x == 3
  "b"
elsif x == 10
  "c"
end
Answer

"c"


  1. What does this statement evaluate to?
x = 10
if x == 2
  "a"
elsif x == 3
  "b"
else
  "c"
end
Answer

"c"


  1. What does this statement evaluate to?
x = 10
if x == 2
  "a"
elsif x == 10
  "b"
else
  "c"
end
Answer

"b"


  1. What does this statement evaluate to?
x = 10
if x == 2
  "a"
elsif x == 3
  "b"
end
Answer

nil


  1. What does this code output?
if false
  x = 1
end
p x
Answer

nil


  1. What does this code output?
if false
  x = 1
end
p y
Answer

NameError (undefined local variable or method 'y' for main:Object)


  1. What does this code output?
if (x = 2)
  puts "Hello"
else
  puts "World"
end
Answer

"Hello"


  1. 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"


  1. 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"


  1. What method is called on an object in a case statement?
Answer

the threequal operator ===, also known as the case equality method


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


  1. True or False: obj1 === obj2 is equivalent to obj2 === obj1, for all objects
Answer

False


  1. True or False: obj1 === obj2 is equivalent to obj1.===(obj2), for all objects
Answer

True


  1. True or False: obj1 === obj2 is equivalent to obj1 == obj2, for all objects
Answer

False


  1. 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"

Loops, Iterators, and Code Blocks

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


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


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


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


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


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


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


  1. True or False: You must explicitly use the keywords do and end when defining a do..end block for while and until and not using curly braces.
Answer

False


  1. True or False: You must explicitly use the keywords do and end when defining a do..end block for loop and not using curly braces.
Answer

True


  1. True or False: The method my_loop as defined below has the same behavior as loop, 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


  1. An iterator is a Ruby method that expects you to provide it with a ______ _______.
Answer

code block


  1. Control passes to the _______ when an iterator yields.
Answer

code block


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


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


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


  1. True or False: If you provide any method with a code block, that method will yield.
Answer

False


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


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


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


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

Exceptions

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


  1. True or False: When an exception is raised, the program is ALWAYS aborted unless you have provided a rescue clause.
Answer

True


  1. Which of the following is the default exception raised by the raise method?
  • A. IOError
  • B. TypeError
  • C. StandardError
  • D. RuntimeError
Answer

D


  1. True or False: NameError, NoMethodError, and TypeError are all classes descended from Exception.
Answer

True


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


  1. Which of the following exceptions are raised by the default method_missing?
  • A. StandardError
  • B. NoMethodError
  • C. ArgumentError
  • D. TypeError
Answer

B


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


  1. True or False: If you use the rescue keyword inside a method or code block, you do not have to use begin explicitly, if you want the rescue clause to apply to the entire method or block.
Answer

True


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


  1. How would you write a rescue statement to rescue an ArgumentError and assign the exception object to the variable e?
begin
  # some code
[YOUR CODE HERE]
  # some code
end
Answer

rescue ArgumentError => e


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


  1. Suppose you created an exception MyCustomError as follows. How would you write code to raise the exception when the array my_array does not include the number 2?
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)


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


  1. True or False: RuntimeError is a descendant of StandardError.
Answer

True

Built-in Essentials

  1. Use two different literal constructors to instantiate a String object with value "hello".
Answer

"hello"
'hello'


  1. Use a literal constructor to instantiate a Symbol with name hello.
Answer

:hello


  1. Use a literal constructor to instantiate an Array with values 1, 2, and 3.
Answer

[1, 2, 3]


  1. 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"}


  1. 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}


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


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


  1. What is the term for things Ruby lets you do to make your code look nicer? (e.g., arr[0] = 3 instead of arr.[]=(0, 3))
Answer

syntactic sugar


  1. Which of the following are methods instead of operators?
  • A. +
  • B. >
  • C. ==
  • D. &&
  • E. ===
  • F. []
  • G. %
Answer

A, B, C, E, F, G


  1. True or False: All methods that end in ! modify their receiver.
Answer

False


  1. True or False: It is considered best practice to only have a bang(!) method when you also have a non-bang equivalent.
Answer

True


  1. True or False: true and false are objects.
Answer

True


  1. True or False: true is the only instance of TrueClass, and false is the only instance of FalseClass
Answer

True


  1. What is the Boolean value of nil?
Answer

false


  1. What is the Boolean value of puts "text"?
Answer

false


  1. What is the Boolean value of def x; end?
Answer

true


  1. What is the Boolean value of class C; end?
Answer

false


  1. What is the Boolean value of class C; 1; end?
Answer

true


  1. What is the Boolean value of x = 10?
Answer

true


  1. What does the == method do, when used to compare two instances of class Object?
Answer

Returns true if their object_ids are identical; false otherwise.

Ruby Docs: == is typically overridden in descendant classes to provide class-specific meaning.


  1. What does the eql? method do, when used to compare two instances of class Object?
Answer

Returns true if their object_ids 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.


  1. What does the equal? method do, when used to compare two instances of class Object?
Answer

Returns true if their object_ids 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.


  1. What does the following code return?
str1 = "text"
str2 = "text"
str1 == str2
Answer

true


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


  1. What class provides full comparison functionality in Ruby?
Answer

Comparable


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

Strings and Symbols

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


  1. What does the following code return?
str = "pizza"
str[2]
Answer

"z"


  1. What does the following code return?
str = "pizza"
str[2, 3]
Answer

"zza"


  1. What does the following code return?
str = "The Wandering Earth"
str[1..6]
Answer

"he Wan"


  1. What does the following code output?
str = "The Wandering Earth"
str[1..2] = 'en'
puts str
Answer

"Ten Wandering Earth"


  1. 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."


  1. 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."


  1. What does the following code return?
str = "1234567890"
str[-4..-1]
Answer

"7890"


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


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


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


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


  1. What does the following code return? "I want pizza".upcase
Answer

"I WANT PIZZA"


  1. What does the following code return? "Mr. Bird".downcase
Answer

"mr. bird"


  1. What does the following code return? "Mr. Bird".swapcase
Answer

"mR. bIRD"


  1. What does the following code return? "hello world".capitalize
Answer

"Hello world"


  1. What does the following code return? "hello".rjust(10)
Answer

" hello" (5 spaces + "hello")


  1. What does the following code return? "hello".ljust(10)
Answer

"hello " ("hello" + 5 spaces)


  1. What does the following code return? "hello".center(9)
Answer

" hello " (2 spaces + "hello" + 2 spaces)


  1. What does the following code return? "hello".center(9, '<>')
Answer

"<>hello<>"


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


  1. True or False: Symbols are immutable. You cannot alter a given symbol.
Answer

True


  1. True or False: When you see :abc in two places in the code, they refer to the same object.
Answer

True


  1. True or False: You can create a new symbol by using the literal constructor (e.g., :abc) or calling the new 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."


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


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

Arrays

  1. Create an Array with elements 1, 2, 3, 4, 5 using the Array.new method.
Answer

Array.new([1, 2, 3, 4, 5])


  1. Create an Array with elements 1, 2, 3, 4, 5 using the literal array constructor.
Answer

[1, 2, 3, 4, 5]


  1. What does the following code return? Array.new(2)
Answer

[nil, nil]


  1. What does the following code return? Array.new(3, "hello")
Answer

["hello", "hello", "hello"]


  1. What does the following code return? n = 0; Array.new(3) {n += 2; "#{n} dogs"}
Answer

["2 dogs", "4 dogs", "6 dogs"]


  1. When you run Array.new(3, "hello") are the resulting objects in the Array the same object, or different objects?
Answer

same object


  1. When you run Array.new(3) {"hello"} are the resulting objects in the Array the same object, or different objects?
Answer

different objects


  1. What does the following code return? [1, 2, 3][1]
Answer

2


  1. What does the following code return? %w{ Did you get that? }
Answer

["Did", "you", "get", "that?"]


  1. What does the following code return? %w{ orange\ juice carrots oatmeal }
Answer

["orange juice", "carrots", "oatmeal"]


  1. What does the following code return? %w{ The cost is $#{5 + 10} }
Answer

["The", "cost", "is", "$\#{5", "+", "10}"]


  1. What does the following code return? %W{ The cost is $#{5 + 10} }
Answer

["The", "cost", "is", "$15"]


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


  1. What does the following code return? %i{ a b c }
Answer

[:a, :b, :c]


  1. What does the following code return? %I{ #{"ab" + "cd"} }
Answer

[:abcd]


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


  1. What does the following code return? %w{ a b c d e f }[2, 3]
Answer

["c", "d", "e"]


  1. What does the following code return? %w{ a b c d e f }[5, 2]
Answer

["f"]


  1. What does the following code return? %w{ a b c d e f }[-3, 3]
Answer

["d", "e", "f"]


  1. What does the following code return? %w{ a b c d e f }[0..3]
Answer

["a", "b", "c", "d"]


  1. What does the following code return? %w{ a b c d e f }[4..-1]
Answer

["e", "f"]


  1. What does the following code output?
arr = ["eagle", 10, :d, "hello world"]
arr[2] = "beast"
p arr
Answer

["eagle", 10, "beast", "hello world"]


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


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


  1. What method can you use to insert an object at the beginning of an array?
Answer

unshift


  1. What method can you use to remove the object at the beginning of an array?
Answer

shift


  1. What methods can you use to insert an object at the end of an array? Name two.
Answer

push, <<, append


  1. What method can you use to remove the last object from an array?
Answer

pop


  1. What does the following code return? [1, 2, 3].push([4, 5, 6])
Answer

[1, 2, 3, [4, 5, 6]]


  1. What does the following code return? [1, 2, 3].concat([4, 5, 6])
Answer

[1, 2, 3, 4, 5, 6]


  1. 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 or b are modified. A new object is created and returned.
Answer

A


  1. 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 or b are modified. A new object is created and returned.
Answer

C


  1. What does the following code return? [1, 2, 3].reverse
Answer

[3, 2, 1]


  1. What does the following code return? [1, 2, [3], [4, [5, [6]]]].flatten
Answer

[1, 2, 3, 4, 5, 6]


  1. What does the following code return? [1, 2, [3], [4, [5, [6]]]].flatten(1)
Answer

[1, 2, 3, 4, [5, [6]]]


  1. What does the following code return? [1, 2, [3], [4, [5, [6]]]].flatten(2)
Answer

[1, 2, 3, 4, 5, [6]]


  1. What does the following code return? ["pizza", :abc, 33].join
Answer

"pizzaabc33"


  1. What does the following code return? ["pizza", :abc, 33].join(", ")
Answer

"pizza, abc, 33"


  1. What does the following code return? ["pizza", :abc, 33] * "-"
Answer

"pizza-abc-33"


  1. What does the following code return? [3, 4, 4, 5, 5, 4, 3].uniq
Answer

[3, 4, 5]


  1. What Array method can you use to return a new array identical to the original array, with all occurrences of nil removed? e.g., [12, 3, nil, 4, nil].method => [12, 3, 4]
Answer

compact


  1. What Array method can you use to return the number of elements in the array?
Answer

size or length


  1. What Array method can you use to return true if the caller is an empty array and false otherwise?
Answer

empty?


  1. What Array method can you use to return true if the array includes at least one occurrence of the item, and false otherwise? e.g., [1, 2, 3].method(2) => true
Answer

include?


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


  1. What Array method can you use to return the first n items in the array?
Answer

take or first


  1. What Array method can you use to return the last n items in the array?
Answer

last


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

Hashes

  1. Create an empty hash using the literal constructor.
Answer

{}


  1. Create an empty hash with default values of 0 using the Hash.new method.
Answer

Hash.new(0)


  1. Create a hash with key and value pairs ("one","a"), ("two","b") using the Hash.[] method.
Answer

Hash["one", "a", "two", "b"] or Hash[[["one", "a"], ["two", "b"]]]


  1. Create a hash with key and value pairs (:a: 12), (:b, 30) using the literal constructor and hash rockets. (=>)
Answer

{:a => 12, :b => 30}


  1. 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}


  1. Suppose you have an empty hash sounds. Add the key and value pair (:cow, "moo") to the sounds hash using the []= method and syntactical sugar.
Answer

sounds[:cow] = "moo"


  1. Suppose you have an empty hash sounds. Add the key and value pair (:cow, "moo") to the sounds hash using the store method.
Answer

sounds.store(:cow, "moo")


  1. Which of the following are required to be unique in hashes? Select all that apply.
  • A. keys
  • B. values
  • C. neither
Answer

A


  1. What does the following code output?
hash = {"Jake" => "octopus", "Chandler" => "chicken"}
hash["Jake"] = "snake" 
puts hash["Jake"]
Answer

"snake"


  1. What is returned from executing the following code?
hash = {"Jake" => "octopus", "Chandler" => "chicken"}
hash["Doreen"]
Answer

nil


  1. What is returned from executing the following code?
hash = {"Jake" => "octopus", "Chandler" => "chicken"}
hash.fetch("Doreen")
Answer

KeyError (key not found: "Doreen")


  1. What is returned from executing the following code?
hash = Hash.new("dog")
hash["Doreen"]
Answer

"dog"


  1. What is returned from executing the following code?
hash = Hash.new("dog")
hash.fetch("Doreen")
Answer

KeyError (key not found: "Doreen")


  1. What is returned from executing the following code?
hash = Hash.new("dog")
hash.fetch("Doreen", "monkey")
Answer

"monkey"


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


  1. What does the following code output?
hash = Hash.new {|h,k| h[k] = 0}
hash[:a]
p hash
Answer

{:a => 0}


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


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


  1. Given the hash my_hash, use the select method to return a new hash containing only those elements from my_hash where the value is greater than 10. Assume all values in my_hash are Integers.
Answer

my_hash.select {|_,v| v > 10}


  1. Given the hash my_hash, use the reject method to return a new hash containing all of the elements from my_hash except those where the key is less than 100. Assume all keys in my_hash are Integers.
Answer

my_hash.reject {|k, _| k < 100}


  1. Name at least 2 methods that return true if the hash h includes the key k, as expressed in this usage: h.method(k)
Answer

has_key?, key?, include?, member?


  1. Name at least 1 method that returns true if the hash h includes the value v, as expressed in this usage: h.method(v)
Answer

has_value?, value?

Ranges and Sets

  1. Use the literal constructor to create a range of the numbers 1, 2, 3, 4, 5.
Answer

(1..5) or (1...6)


  1. What is the difference between 1..10 and 1...10?
Answer

1..10 includes 10. 1...10 does not.


  1. Which Range method returns true 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?


  1. Which Range method treats the range as a collection of values, and returns true if the argument to the method is among the values in the collection?
Answer

include?


  1. Which of the following statements return true, given r = "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


  1. Which of the following statements return true, given r = "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


  1. Which of the following statements return true, given r = "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


  1. Which of the following statements return true, given r = "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


  1. Which of the following statements return true, given r = 1..100? Select all that apply.
  • A. r.cover?(3)
  • B. r.cover?(5.5)
  • C. None of the above
Answer

A, B


  1. Which of the following statements return true, given r = 1..100? Select all that apply.
  • A. r.include?(3)
  • B. r.include?(5.5)
  • C. None of the above
Answer

A


  1. Which of the following statements return true, given r = 100..1? Select all that apply.
  • A. r.cover?(3)
  • B. r.cover?(5.5)
  • C. None of the above
Answer

C


  1. Which of the following statements return true, given r = 100..1? Select all that apply.
  • A. r.include?(3)
  • B. r.include?(5.5)
  • C. None of the above
Answer

C


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


  1. Create a set using the Set.new constructor, with the elements "banana", "bagel", and "lettuce".
Answer

Set.new(["banana", "bagel", "lettuce"])


  1. Is there a literal constructor for sets?
Answer

No, because sets are part of the standard library, not the core.


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


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


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


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


  1. What Set method is an alias for <<?
Answer

add


  1. What is the difference between the Set methods add and add??
Answer

If the set is unchanged after the operation, add would return the set but add? would return nil.


  1. Suppose you have the sets set_a and set_b. Write a statement that returns a new set containing only the elements that appear in both set_a and set_b. Use a Set method.
Answer

set_a & set_b or set_a.intersection(set_b)


  1. Suppose you have the sets set_a and set_b. Write a statement that returns a new set containing items that appear in either set_a or set_b, or both. Use a Set method.
Answer

set_a | set_b, set_a + set_b, or set_a.union(set_b)


  1. Suppose you have the sets set_a and set_b. Write a statement that returns all items in set_a that do not show up in in set_b. Use a Set method.
Answer

set_a - set_b or set_a.difference(set_b)


  1. Suppose you have the sets set_a and set_b. Write a statement that returns the items that only show up in either set_a or set_b but not both. Use a Set method.
Answer

set_a ^ set_b or (set_a | set_b) - (set_a & set_b)


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


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

Regular Expressions

There are multiple ways to answer some of these questions. Test your answers in irb if they differ from the given answers.

  1. What does the following code return? /abc/.match("Hello abcdefg").class
Answer

MatchData


  1. What does the following code return? "Hello abcdefg".match(/abc/).class
Answer

MatchData


  1. What does the following code return? "Hello abcdefg".match(/123/)
Answer

nil


  1. What does the following code return? /123/.match("Hello abcdefg")
Answer

nil


  1. What does the following code return? /abc/ =~ "Alpha abc"
Answer

6


  1. True or False: /abc/ =~ "Alpha abc" is equivalent to "Alpha abc" =~ /abc/
Answer

True


  1. 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 \


  1. What special character can you use to match any character, except newline?
Answer

The dot wildcard character .


  1. 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/


  1. True or False: /[br]ead/ =~ "bread" returns nil.
Answer

False


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


  1. There exists special escape sequences for some common character sequences. What is the special escape sequence to match any digit?
Answer

\d


  1. What is the special escape sequence to match any digit, alphabetical character, or underscore?
Answer

\w


  1. What is the special escape sequence to match any whitespace character (space, tab, newline)?
Answer

\s


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


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


  1. 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]+)/


  1. 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]+)/


  1. Suppose you have a MatchData object m containing some captures. What are two ways you can access the third capture?
Answer

m[3] or m.captures[2]


  1. Suppose you have a MatchData object containing some captures. What MatchData method can you use to get the part of the string before the part that matched? What MatchData method can you use to get the part of the string after the part that matched?
Answer

pre_match; post_match


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


  1. Write a pattern that uses the zero-or-one quantifier to match either "hi", "his", but NOT "hiss".
Answer

/his?/


  1. Write a pattern that uses the zero-or-more quantifier to match either "hi", "his", "hiss", or "hissssssss".
Answer

/his*/


  1. Write a pattern that uses the one-or-more quantifier to match any sequence of one or more consecutive digits.
Answer

/\d+/


  1. Write a pattern that matches exactly 5 digits, followed by a hyphen(-), followed by exactly 4 digits.
Answer

/\d{5}-\d{4}/


  1. 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}/


  1. Write a pattern that matches exactly 2 digits, followed by a hyphen(-), followed by 5 or more digits.
Answer

/\d{2}-\d{5,}/


  1. What is the anchor for beginning of line? What is the anchor for end of line?
Answer

^; $


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


  1. What is the anchor for word boundary?
Answer

\b


  1. Write a pattern to match either "abc" or "ABC". Use the case-insensitive modifier.
Answer

/abc/i


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


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

Procs and Lambdas

  1. Create a Proc object by instantiating the Proc class with a code block {puts "Hello"}.
Answer

Proc.new {puts "Hello"}


  1. True or False: When you create a Proc object, you must supply a code block.
Answer

True


  1. True or False: Every code block serves as the basis of a proc.
Answer

False


  1. True or False: A code block is an object.
Answer

False


  1. True or False: Procs can serve as code blocks.
Answer

True


  1. What does the & in my_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.


  1. Suppose you have an array of words, words. How would you use the Symbol#to_proc method to return a new array where each word in words is capitalized?
Answer

words.map(&:capitalize)


  1. True or False: array.map(&:to_i) is equivalent to array.map {|x| x.to_i}
Answer

True


  1. True or False: array.map(&:to_i) is equivalent to array.map {|x| x.send(:to_i)}
Answer

True


  1. What is the term for a piece of code that carries its creation context around with it?
Answer

closure


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


  1. True or False: Procs enforce argument count.
Answer

False


  1. True or False: The lambda method returns a Proc object.
Answer

True


  1. True or False: Lambdas enforce argument count.
Answer

True


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


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


  1. Instantiate a lambda using the lambda method, with a code block { puts "Hi" }.
Answer

lambda {puts "Hi"}


  1. Instantiate a lambda using the "stabby lambda" literal constructor, with a code block { puts "Hi" }.
Answer

-> {puts "Hi"}

About

Created 346 Ruby questions based on content from The Well-Grounded Rubyist

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages