RbRuby

Ruby quiz – 40 questions with answers

Try it interactively

With scoring, random questions, and saved progress – or go straight to the timed exam with certificate.

Beginner (14 questions)

Which method prints a line to the console in Ruby?

  1. echo "Hi"
  2. puts "Hi"
  3. console.log("Hi")
  4. printf("Hi")
Show answer

Correct: puts "Hi"

puts prints the value with a line break. print leaves out the break, p shows the debug representation.

What is :name in Ruby?

  1. A variable
  2. A symbol
  3. A string that can be changed
  4. A constant
Show answer

Correct: A symbol

Symbols are immutable names that exist in memory only once – ideal as hash keys.

What does this code print?

puts 7 / 2
  1. 3.5
  2. 3
  3. 4
  4. 3.0
Show answer

Correct: 3

Two integers are divided using integer division: 3. For 3.5 you need 7.0 / 2 or 7.fdiv(2).

What does this code print?

puts "Ruby" * 2
  1. RubyRuby
  2. Ruby2
  3. Error
  4. Ruby Ruby
Show answer

Correct: RubyRuby

String * number repeats the string.

What does this code print?

puts [1, 2, 3].map { |x| x * 2 }.inspect
  1. [1, 2, 3]
  2. [2, 4, 6]
  3. 6
  4. [1, 4, 9]
Show answer

Correct: [2, 4, 6]

map transforms every element and returns a new array: [2, 4, 6].

Which values count as falsy in Ruby?

  1. nil and false
  2. 0, "" and nil
  3. nil, false and 0
  4. only false
Show answer

Correct: nil and false

Only nil and false are falsy. Even 0 and the empty string are truthy.

What does this code print?

puts 0 ? "truthy" : "falsy"
  1. truthy
  2. falsy
  3. nil
  4. Error
Show answer

Correct: truthy

0 is truthy in Ruby – unlike in Python, PHP or JavaScript.

What does this code print?

3.times { |i| print i }
  1. 012
  2. 123
  3. 0 1 2
  4. 321
Show answer

Correct: 012

times counts from 0 to 2, print outputs without a separator.

How does a single-line comment begin in Ruby?

  1. //
  2. #
  3. --
  4. /*
Show answer

Correct: #

Single-line comments begin with #.

What does this code print?

puts 'Value: #{1 + 2}'
  1. Value: 3
  2. Value: #{1 + 2}
  3. Value: 1 + 2
  4. Error
Show answer

Correct: Value: #{1 + 2}

No interpolation takes place in single quotes. With double quotes you would get Value: 3.

What does the question mark in gerade? usually mean?

  1. The method is private
  2. The method returns true or false
  3. The method can return nil
  4. The method is deprecated
Show answer

Correct: The method returns true or false

Convention: methods with ? are queries and return a boolean (empty?, include?).

What does this code print?

puts "Ruby".upcase.reverse
  1. ybur
  2. YBUR
  3. RUBY
  4. Ruby
Show answer

Correct: YBUR

First upcase (RUBY), then reverse (YBUR). Methods are chained from left to right.

What does this code print?

def f
  1
  2
end
puts f
  1. 1
  2. 2
  3. nil
  4. Error
Show answer

Correct: 2

The value of the last expression is the return value of the method – here 2.

What does this code print?

a = [1, 2, 3]
puts a[-1]
  1. 1
  2. 3
  3. -1
  4. nil
Show answer

Correct: 3

Negative indices count from the end: -1 is the last element.

Intermediate (14 questions)

What does this code print?

def f
  yield 1
  yield 2
end
f { |x| print x * 10 }
  1. 1020
  2. 10 20
  3. 30
  4. 12
Show answer

Correct: 1020

yield calls the block twice (with 1 and 2); print writes 10 and 20 without a separator: 1020.

What does &:upcase do in %w[a b].map(&:upcase)?

  1. It calls upcase on every element (Symbol#to_proc)
  2. It creates a symbol :upcase
  3. It changes the method upcase
  4. It is a syntax error
Show answer

Correct: It calls upcase on every element (Symbol#to_proc)

&:upcase turns the symbol into a block that calls upcase on the element – short for { |x| x.upcase }.

What does this code print?

puts [1, 2, 3, 4].select(&:even?).sum
  1. 6
  2. 10
  3. 2
  4. 4
Show answer

Correct: 6

select keeps 2 and 4, sum adds them: 6.

What does this code print?

puts [2, 3, 4].reduce(1) { |a, b| a * b }
  1. 9
  2. 24
  3. 10
  4. 1
Show answer

Correct: 24

reduce starts with 1 and multiplies: 1·2·3·4 = 24.

What does attr_accessor :name create in a class?

  1. Only a getter
  2. Only a setter
  3. Getter and setter for @name
  4. A constant NAME
Show answer

Correct: Getter and setter for @name

attr_accessor creates name and name=; attr_reader only the getter, attr_writer only the setter.

What does this code print?

puts :a.object_id == :a.object_id
  1. true
  2. false
  3. nil
  4. Error
Show answer

Correct: true

A symbol exists only once in memory, so the object_id is always the same. For strings it would be false.

What does this code print?

P = Struct.new(:x, :y)
puts P.new(1, 2) == P.new(1, 2)
  1. true
  2. false
  3. Error
  4. nil
Show answer

Correct: true

Struct compares instances by their values, not their identity.

What happens with ->(a, b) { a + b }.call(1)?

  1. The result is 1
  2. b becomes nil and a TypeError is raised
  3. An ArgumentError, because a lambda checks the number of arguments
  4. The result is nil
Show answer

Correct: An ArgumentError, because a lambda checks the number of arguments

Lambdas behave like methods and raise an ArgumentError for the wrong number of arguments. A Proc would be generous.

What does this code print?

h = Hash.new(0)
"abca".each_char { |c| h[c] += 1 }
puts h["a"]
  1. 2
  2. 1
  3. 0
  4. nil
Show answer

Correct: 2

Hash.new(0) returns 0 for new keys; "a" occurs twice.

What does this code print?

puts [1, 2, 3].each_slice(2).to_a.inspect
  1. [[1, 2], [3]]
  2. [[1, 2], [2, 3]]
  3. [1, 2, 3]
  4. [[1], [2], [3]]
Show answer

Correct: [[1, 2], [3]]

each_slice(2) splits into chunks of size 2; the last chunk is shorter. each_cons(2) would be overlapping pairs.

What does this code print?

def hallo(name = "World", gruss: "Hello")
  "#{gruss}, #{name}!"
end
puts hallo(gruss: "Hi")
  1. Hi, World!
  2. Hello, Hi!
  3. Hi!
  4. Error
Show answer

Correct: Hi, World!

The keyword argument gruss: is set, name keeps its default value "World".

What does extend Modul do in a class?

  1. It turns the module methods into class methods
  2. It turns the module methods into instance methods
  3. It copies the module into a file
  4. It inherits from the module
Show answer

Correct: It turns the module methods into class methods

include provides instance methods, extend class methods (the methods end up in the singleton of the class).

What happens when you call a private method with an explicit receiver (obj.geheim)?

  1. It runs normally
  2. NoMethodError
  3. ArgumentError
  4. It returns nil
Show answer

Correct: NoMethodError

Private methods can only be called without an explicit receiver (implicitly on self), otherwise a NoMethodError occurs.

What does this code print?

begin
  Integer("x")
rescue ArgumentError
  puts "A"
ensure
  puts "B"
end
  1. A
  2. B
  3. A and B (two lines)
  4. Error
Show answer

Correct: A and B (two lines)

The exception is caught ("A"), ensure always runs ("B").

Advanced (12 questions)

What is bundle exec used for?

  1. It installs gems globally
  2. It runs a command with the gem versions from the Gemfile.lock
  3. It compiles Ruby code
  4. It updates all gems
Show answer

Correct: It runs a command with the gem versions from the Gemfile.lock

bundle exec makes sure that exactly the versions specified in the lockfile are used – not some globally installed one.

What does gem "sinatra", "~> 4.0" mean in the Gemfile?

  1. Exactly version 4.0
  2. Version 4.0 or higher, but below 5.0
  3. Everything below version 4.0
  4. Any version except 4.0
Show answer

Correct: Version 4.0 or higher, but below 5.0

The pessimistic operator ~> allows updates of the last specified digit: >= 4.0 and < 5.0.

What is the file Gemfile.lock used for?

  1. It protects the project with a password
  2. It records the exactly resolved gem versions for reproducible installations
  3. It contains the Ruby source code of the gems
  4. It blocks updates permanently
Show answer

Correct: It records the exactly resolved gem versions for reproducible installations

When resolving, Bundler writes all versions into the lockfile. bundle install then installs exactly the same versions from it again.

Why should you also implement respond_to_missing? with method_missing?

  1. Otherwise method_missing does not run
  2. So that respond_to? and method(...) answer correctly
  3. To make the method faster
  4. It is only needed for private methods
Show answer

Correct: So that respond_to? and method(...) answer correctly

Without respond_to_missing?, respond_to? claims that the dynamic method does not exist – this breaks duck typing and tools.

What does this code print?

class A
  %w[x y].each { |n| define_method("#{n}?") { true } }
end
puts A.new.y?
  1. true
  2. false
  3. nil
  4. NoMethodError
Show answer

Correct: true

define_method creates the methods x? and y? at runtime; y? returns the block value true.

Which table does the model Article belong to in Rails by default?

  1. article
  2. articles
  3. Articles
  4. tbl_article
Show answer

Correct: articles

Convention over configuration: the class name in the singular becomes the table name in the plural and lowercase: articles.

What is the "N+1 problem" with ActiveRecord?

  1. Too many gems in the Gemfile
  2. For each record of a list, an additional query for associated data is executed
  3. An error when migrating N tables
  4. A limit of N+1 records per query
Show answer

Correct: For each record of a list, an additional query for associated data is executed

One query loads the list (1), then one per element for the association (N). Remedy: includes/preload.

What does this code print?

puts [1, 2, 3].lazy.map { |x| x * 2 }.first(2).inspect
  1. [2, 4]
  2. [2, 4, 6]
  3. [1, 2]
  4. #<Enumerator::Lazy>
Show answer

Correct: [2, 4]

lazy only evaluates as many elements as first(2) asks for; the result is a normal array [2, 4].

What does the GVL/GIL do in CRuby?

  1. It prevents several threads from executing Ruby code at the same time
  2. It encrypts gems
  3. It sorts methods
  4. It prevents memory leaks
Show answer

Correct: It prevents several threads from executing Ruby code at the same time

Because of the Global VM Lock, only one thread runs Ruby code at a time in CRuby. Threads still help for I/O; for parallelism you use processes or Ractors.

What does this code print?

module M
  def hi
    "M"
  end
end

class C
  prepend M

  def hi
    "C"
  end
end
puts C.new.hi
  1. M
  2. C
  3. MC
  4. Error
Show answer

Correct: M

prepend places the module in front of the class in method resolution: M#hi wins. With include you would get "C".

What happens here?

# frozen_string_literal: true
s = "a"
s << "b"
  1. s becomes "ab"
  2. FrozenError
  3. TypeError
  4. s stays "a", without an error
Show answer

Correct: FrozenError

The magic comment freezes all string literals; appending with << raises a FrozenError. With +"a" you would get a mutable string.

What does this code print?

case [1, [2, 3]]
in [a, [b, *]]
  puts a + b
end
  1. 3
  2. 6
  3. 1
  4. NoMatchingPatternError
Show answer

Correct: 3

The pattern binds a = 1 and b = 2 (the rest 3 is ignored with *): 1 + 2 = 3.