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?
- echo "Hi"
- puts "Hi"
- console.log("Hi")
- 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?
- A variable
- A symbol
- A string that can be changed
- 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- 3.5
- 3
- 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- RubyRuby
- Ruby2
- Error
- 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, 2, 3]
- [2, 4, 6]
- 6
- [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?
- nil and false
- 0, "" and nil
- nil, false and 0
- 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"- truthy
- falsy
- nil
- 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 }- 012
- 123
- 0 1 2
- 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?
- //
- #
- --
- /*
Show answer
Correct: #
Single-line comments begin with #.
What does this code print?
puts 'Value: #{1 + 2}'- Value: 3
- Value: #{1 + 2}
- Value: 1 + 2
- 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?
- The method is private
- The method returns true or false
- The method can return nil
- 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- ybur
- YBUR
- RUBY
- 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
- 2
- nil
- 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
- 3
- -1
- 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 }- 1020
- 10 20
- 30
- 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)?
- It calls upcase on every element (Symbol#to_proc)
- It creates a symbol :upcase
- It changes the method upcase
- 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- 6
- 10
- 2
- 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 }- 9
- 24
- 10
- 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?
- Only a getter
- Only a setter
- Getter and setter for @name
- 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- true
- false
- nil
- 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)- true
- false
- Error
- nil
Show answer
Correct: true
Struct compares instances by their values, not their identity.
What happens with ->(a, b) { a + b }.call(1)?
- The result is 1
- b becomes nil and a TypeError is raised
- An ArgumentError, because a lambda checks the number of arguments
- 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"]- 2
- 1
- 0
- 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, 2], [3]]
- [[1, 2], [2, 3]]
- [1, 2, 3]
- [[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")- Hi, World!
- Hello, Hi!
- Hi!
- 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?
- It turns the module methods into class methods
- It turns the module methods into instance methods
- It copies the module into a file
- 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)?
- It runs normally
- NoMethodError
- ArgumentError
- 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- A
- B
- A and B (two lines)
- 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?
- It installs gems globally
- It runs a command with the gem versions from the Gemfile.lock
- It compiles Ruby code
- 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?
- Exactly version 4.0
- Version 4.0 or higher, but below 5.0
- Everything below version 4.0
- 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?
- It protects the project with a password
- It records the exactly resolved gem versions for reproducible installations
- It contains the Ruby source code of the gems
- 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?
- Otherwise method_missing does not run
- So that respond_to? and method(...) answer correctly
- To make the method faster
- 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?- true
- false
- nil
- 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?
- article
- articles
- Articles
- 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?
- Too many gems in the Gemfile
- For each record of a list, an additional query for associated data is executed
- An error when migrating N tables
- 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- [2, 4]
- [2, 4, 6]
- [1, 2]
- #<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?
- It prevents several threads from executing Ruby code at the same time
- It encrypts gems
- It sorts methods
- 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- M
- C
- MC
- 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"- s becomes "ab"
- FrozenError
- TypeError
- 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- 3
- 6
- 1
- NoMatchingPatternError
Show answer
Correct: 3
The pattern binds a = 1 and b = 2 (the rest 3 is ignored with *): 1 + 2 = 3.