Ruby interview questions

25 questions from the Ruby course, each with the correct answer and an explanation. Try to answer before you open the answer.

Getting Started with Ruby

1. Which statement about Ruby is true?

  1. Everything, including numbers and nil, is an object
  2. Only some values are objects
  3. Ruby is statically typed
  4. Ruby cannot be used for web development
Show answer

Answer: Everything, including numbers and nil, is an object

Ruby has a uniform object model: every value responds to methods.

Lesson: What Ruby Is and Why Developers Love It

2. What does bundle exec do?

  1. Installs Ruby
  2. Publishes a gem
  3. Formats code
  4. Runs a command using exactly the gem versions recorded in Gemfile.lock
Show answer

Answer: Runs a command using exactly the gem versions recorded in Gemfile.lock

bundle exec ensures the locked dependency versions are used.

Lesson: Installing Ruby, irb, Gems and Bundler

3. Which values are falsy in Ruby?

  1. 0, "", nil and false
  2. Only false
  3. Only nil and false
  4. nil, false and empty arrays
Show answer

Answer: Only nil and false

Ruby treats every value except nil and false as true in conditions.

Lesson: Variables, nil, Strings and Symbols

Control Flow, Collections and Blocks

4. Which operator does case/when use to compare the value with each when clause?

  1. ==
  2. equal?
  3. ===
  4. <=>
Show answer

Answer: ===

when clauses call pattern === value, which ranges, classes and regexes implement meaningfully.

Lesson: Conditionals, case and Ranges

5. What does `orders.map(&:id)` do?

  1. Deletes ids
  2. Calls the id method on each element and returns an array of the results
  3. Sorts by id
  4. It is a syntax error
Show answer

Answer: Calls the id method on each element and returns an array of the results

&:symbol converts the method name into a block that calls it on each element.

Lesson: Arrays, Hashes and Enumerable

6. How does a lambda differ from a proc in Ruby?

  1. Lambdas check argument counts strictly and return only from themselves
  2. Lambdas cannot capture variables
  3. Procs are faster
  4. There is no difference
Show answer

Answer: Lambdas check argument counts strictly and return only from themselves

Lambdas behave like methods; procs are lenient and return from the enclosing method.

Lesson: Blocks, yield, Procs and Lambdas

Objects, Classes and Modules

7. What does attr_reader :number create?

  1. A getter method number that returns @number
  2. A setter only
  3. A class variable
  4. A constant
Show answer

Answer: A getter method number that returns @number

attr_reader defines a reader method for the instance variable.

Lesson: Classes, Attributes and Initialisation

8. What do you need to define to gain Enumerable methods such as map and select in your class?

  1. to_s
  2. <=>
  3. initialize only
  4. each
Show answer

Answer: each

Enumerable builds all its methods on top of each.

Lesson: Modules, Mixins and Namespaces

9. What does Data.define (Ruby 3.2+) create?

  1. A database table
  2. A mutable struct with setters
  3. An immutable value-object class with value equality
  4. A module
Show answer

Answer: An immutable value-object class with value equality

Data classes are frozen value objects with keyword construction and equality by value.

Lesson: Inheritance, Visibility, Struct and Data

Methods, Errors and Pattern Matching

10. In `def connect(host:, port: 443)`, which statement is true?

  1. Both are optional
  2. host is positional
  3. host is a required keyword argument; port is optional with a default
  4. It is a syntax error
Show answer

Answer: host is a required keyword argument; port is optional with a default

A keyword without a default value is required.

Lesson: Method Arguments and Conventions

11. Why should you rescue StandardError rather than Exception?

  1. Exception does not exist
  2. Exception also catches signals and SystemExit, making programs hard to interrupt or exit
  3. StandardError is faster
  4. Ruby forbids rescuing Exception
Show answer

Answer: Exception also catches signals and SystemExit, making programs hard to interrupt or exit

Rescuing Exception swallows interrupts and exit requests, not just application errors.

Lesson: Exceptions and Error Handling

12. How does `case ... in` differ from `case ... when`?

  1. in matches structure and binds variables, while when compares values with ===
  2. They are identical
  3. in only works with integers
  4. when supports guards but in does not
Show answer

Answer: in matches structure and binds variables, while when compares values with ===

Pattern matching destructures arrays, hashes and objects and can bind parts to variables.

Lesson: Pattern Matching with case/in

Dynamic Ruby and Metaprogramming

13. What does duck typing mean in Ruby?

  1. Code depends on what methods an object responds to, not on its class
  2. Objects must inherit from Duck
  3. All variables must declare types
  4. Only classes can be passed to methods
Show answer

Answer: Code depends on what methods an object responds to, not on its class

If it responds to the right methods, it can be used.

Lesson: Duck Typing, Open Classes and Refinements

14. What should you define alongside method_missing?

  1. initialize
  2. to_s
  3. each
  4. respond_to_missing? so respond_to? reports dynamic methods correctly
Show answer

Answer: respond_to_missing? so respond_to? reports dynamic methods correctly

respond_to_missing? keeps introspection consistent with the dynamic behaviour.

Lesson: Metaprogramming: send, define_method and method_missing

15. How do many Ruby DSLs make bare method calls inside a block reach a builder object?

  1. By using global variables
  2. By compiling the block to C
  3. By running the block with instance_eval or instance_exec so self is the builder
  4. By using threads
Show answer

Answer: By running the block with instance_eval or instance_exec so self is the builder

instance_eval changes self for the block, routing implicit calls to the builder.

Lesson: Blocks and DSLs

Files, Text and Concurrency

16. Why use the block form File.open(path, "w") { |f| ... }?

  1. It is faster
  2. It encrypts the file
  3. The file is closed automatically when the block ends, even if an error occurs
  4. It is the only way to write files
Show answer

Answer: The file is closed automatically when the block ends, even if an error occurs

Block forms guarantee resource cleanup.

Lesson: Files, JSON, CSV and Time

17. Which anchors match the start and end of the entire string in a Ruby regex?

  1. ^ and $
  2. \A and \z
  3. < and >
  4. \b and \B
Show answer

Answer: \A and \z

^ and $ match at line boundaries; \A and \z anchor the whole string.

Lesson: Strings, Regular Expressions and Encodings

18. In CRuby, when do threads improve performance?

  1. For I/O-bound work such as network or database calls, because the GVL is released while waiting
  2. For CPU-heavy calculations in pure Ruby
  3. Never
  4. Only on Windows
Show answer

Answer: For I/O-bound work such as network or database calls, because the GVL is released while waiting

The GVL limits Ruby code to one thread at a time, but waiting on I/O releases it.

Lesson: Threads, the GVL, Fibers and Ractors

Gems, Testing and Code Quality

19. In Semantic Versioning, which version bump signals a breaking change?

  1. Major (1.2.3 -> 2.0.0)
  2. Patch (1.2.3 -> 1.2.4)
  3. Minor (1.2.3 -> 1.3.0)
  4. None
Show answer

Answer: Major (1.2.3 -> 2.0.0)

Major versions communicate incompatible API changes.

Lesson: Creating and Publishing Gems

20. What does RSpec's instance_double provide over a plain double?

  1. Faster tests
  2. Database access
  3. Automatic test data
  4. Verification that stubbed methods actually exist on the real class with matching arguments
Show answer

Answer: Verification that stubbed methods actually exist on the real class with matching arguments

Verified doubles fail when you stub methods the real class does not define.

Lesson: Testing with RSpec and Minitest

21. What is YJIT?

  1. A testing framework
  2. A package manager
  3. A just-in-time compiler built into CRuby that speeds up Ruby code
  4. A linter
Show answer

Answer: A just-in-time compiler built into CRuby that speeds up Ruby code

YJIT compiles hot Ruby code to machine code at run time.

Lesson: RuboCop, Types and Performance

Rails, Scripting, Idioms and Revision

22. What does Active Record do in Rails?

  1. Renders HTML templates
  2. Handles routing
  3. Maps Ruby classes to database tables and provides queries, validations and associations
  4. Manages JavaScript
Show answer

Answer: Maps Ruby classes to database tables and provides queries, validations and associations

Active Record is Rails' ORM layer for models.

Lesson: A First Look at Ruby on Rails

23. Why prefer Open3.capture3("cmd", arg) over a backtick command with interpolated input?

  1. It is shorter
  2. Arguments are passed directly without a shell, preventing command injection, and you get stdout, stderr and status
  3. Backticks do not work in Ruby
  4. It runs faster on every system
Show answer

Answer: Arguments are passed directly without a shell, preventing command injection, and you get stdout, stderr and status

Passing arguments separately avoids shell interpretation of untrusted input.

Lesson: Automation, Rake and Command-Line Tools

24. What does the safe navigation operator in user&.address do?

  1. Returns nil instead of calling address when user is nil
  2. Raises if user is nil
  3. Creates a new user
  4. Freezes the user object
Show answer

Answer: Returns nil instead of calling address when user is nil

&. short-circuits to nil when the receiver is nil.

Lesson: Idiomatic Ruby and Common Pitfalls

25. Which method do you define to make your own class work with Enumerable?

  1. to_s
  2. initialize
  3. inspect
  4. each
Show answer

Answer: each

Enumerable builds its methods on each.

Lesson: Revision and Interview Questions

← Back to the course