Skip to content
Tutorials Center
My learning

Topics

Lesson 132 of 134 ยท Practice

Ruby Interview Questions

Forty Ruby interview questions with clear answers and runnable code, from truthiness and blocks to the object model, metaprogramming, exceptions and concurrency.

Ruby interviews usually probe the same few ideas: how the language treats objects, what blocks and procs really are, how method lookup works, how errors propagate, and what concurrency means under the GVL. The questions below cover those ideas in roughly the order a conversation tends to go, from warm-up questions to the ones that separate people who have read about Ruby from people who have debugged it.

Each answer is short enough to say out loud in an interview, and several have a runnable example so you can see the behavior instead of memorizing it. When you practice, close the page, answer in your own words, and then compare. If you cannot explain a point in two or three sentences, follow the link to the lesson and read it again.

Language basics

1. What kind of language is Ruby?

Ruby is a dynamically and strongly typed, interpreted, garbage-collected, object-oriented language with functional features. Dynamically typed means variables have no declared type and types are checked when code runs. Strongly typed means Ruby does not silently convert unrelated types: "1" + 1 raises a TypeError. See Introduction to Ruby.

2. What is falsy in Ruby?

Only nil and false. Everything else, including 0, "", [] and {}, is truthy. That is why you write list.empty? and n.zero? rather than if list. See if, elsif, else and unless.

3. What is the difference between a String and a Symbol?

A string is a mutable sequence of characters, and every literal creates a new object. A symbol is an immutable, interned name: :ruby.equal?(:ruby) is always true. Symbols are used as hash keys, method names and options, where identity and speed matter; strings are for text. See Symbols.

4. Explain ==, equal?, eql? and ===.

== compares values (1 == 1.0 is true). equal? compares object identity and should never be overridden. eql? is strict value equality used by Hash for keys (1.eql?(1.0) is false), and must agree with hash. === is the "case equality" operator that case/when uses: Integer === 3, (1..5) === 3 and /r/ === "ruby" are all true. See Equality and Identity.

Ruby Equality, truthiness and pass by reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

5. Does Ruby pass arguments by value or by reference?

Ruby passes a copy of the reference ("pass by object reference"). The method gets its own variable pointing at the same object, so mutating the object (<<) is visible to the caller, while reassigning the parameter (text = "replaced") is not. This is the same model as Python and Java for objects.

6. What do puts, print and p do differently?

puts calls to_s, adds a newline and prints each array element on its own line. print calls to_s without a newline. p calls inspect (so strings keep their quotes), and returns its argument, which makes it ideal for debugging. See Reading Input and Formatting Output.

7. What does ||= do, and what is its pitfall?

a ||= b means a || (a = b): assign only if a is nil or false. It is the standard idiom for defaults and memoization. The pitfall is that false is overwritten too, so flag ||= true cannot keep an explicit false. Use flag = true if flag.nil? or defined? when false is a valid value. See Ternary, Safe Navigation and Short-Circuit.

8. How large can an Integer be?

As large as memory allows. Since Ruby 2.4 Fixnum and Bignum are unified into Integer, so 2**100 just works and nothing overflows. Integer division floors (-7 / 2 is -4) and % takes the sign of the divisor. Floats follow IEEE 754, so 0.1 + 0.2 != 0.3. Use Rational or BigDecimal for exact decimals. See Numbers.

9. Are Ruby strings mutable? What are chilled strings?

Yes, strings are mutable (<<, upcase!, gsub!). Literals without the # frozen_string_literal: true comment are "chilled": they can still be modified in Ruby 4.0, but they are on the path to being frozen by default, so new code should not mutate literals. Use +"" or String.new for a mutable buffer and dup before changing a string you received. See Strings and Immutability and freeze.

10. What is safe navigation?

user&.name calls name only if user is not nil, and otherwise returns nil. It is for values that are legitimately optional. Chains of &. that hide bugs are a smell; if a value must exist, fetch or an explicit check fails closer to the cause.

Blocks, procs and iteration

11. What is the difference between a block, a proc and a lambda?

A block is the code you pass after a method call; it is not an object until you capture it with &block. A Proc is that code as an object. A lambda is a proc created with lambda or ->, with two differences: it checks its argument count strictly, and return leaves only the lambda, while return in a proc leaves the enclosing method.

Ruby Proc versus lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

12. What is a closure?

A closure is a block or lambda together with the local variables that were in scope where it was created. make_counter above returns a lambda that keeps its own n alive after the method returns. Each call to make_counter makes a fresh n. See Closures and Binding.

13. What does yield do, and how is it different from block.call?

yield runs the block passed to the current method, and block_given? tells you whether there is one. &block captures the block as a Proc so you can store it or pass it on. yield is faster and the usual choice; use &block when you need the object. See Blocks.

14. How does map(&:upcase) work?

The & operator calls to_proc on its operand. Symbol#to_proc returns a proc that sends the symbol as a message to its argument, so &:upcase is { |x| x.upcase }. Any object with to_proc works, including a Method object (&method(:puts)).

15. When do you use each, map, select and reduce?

each is for side effects and returns the receiver. map transforms and returns a new array of the same size. select and reject filter. reduce (alias inject) folds to a single value. Specialized methods such as sum, tally, group_by, partition, each_slice and min_by are clearer than hand-written reduce calls. See Iterating and Transforming Arrays.

16. What is a lazy enumerator?

(1..Float::INFINITY).lazy returns an Enumerator::Lazy that computes elements one at a time as the chain map, select, take pulls them, so infinite sequences work and no intermediate arrays are built. Call first(n), take(n).to_a or force to get results. See Enumerators and Lazy Enumerators.

17. What are it and numbered parameters?

In a block without declared parameters, it (Ruby 3.4+) names the single argument, and _1, _2 name positional ones. [1, 2].map { it * 2 } is shorter than { |n| n * 2 }. Use them for short one-line blocks only; name the parameter when the block grows. See Endless Methods and Modern Syntax.

18. What do curry and method objects give you?

method(:name) turns a method into a Method object that you can pass around, call, compose (>>, <<) and convert with &. curry turns a multi-argument lambda into a chain of one-argument calls: add.curry[1][2]. Both support functional style without leaving Ruby's object model. See Procs and Lambdas.

Objects, classes and modules

19. What is the difference between a class and a module?

A class can be instantiated and can be subclassed (one superclass only). A module cannot be instantiated; it holds methods and constants that you mix in (include, extend, prepend), or uses as a namespace. A module is Ruby's answer to multiple inheritance. See Modules and Mixins.

20. What is the difference between include, extend and prepend?

include adds the module's methods as instance methods, placing the module after the class in the ancestor chain. prepend puts the module before the class so it can wrap the class's own methods with super. extend adds the methods to a single object (or to a class as class methods).

21. How does method lookup work?

Ruby looks in the object's singleton class, then walks Class.ancestors in order: prepended modules, the class, included modules (latest included first), then the superclass and so on up to BasicObject. super continues the walk from the next entry. If nothing is found, Ruby calls method_missing. See The Ruby Object Model.

Ruby Method lookup with include and prepend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Read the output from the top: Loud runs first (it was prepended), calls super into Dog, which calls super into Polite, which finally reaches Animal. Then each layer wraps the result on the way back.

22. What do public, protected and private mean?

public methods can be called by anyone. private methods can only be called without an explicit receiver (or on self), but subclasses can call them. protected methods can be called with an explicit receiver only from other instances of the same class family, which is useful for comparisons. Private is about how you call, not who you are. See public, private and protected.

23. What are attr_reader, attr_writer and attr_accessor?

They generate methods: attr_reader :x defines x, attr_writer :x defines x=, and attr_accessor defines both. Instance variables are always private, so these are the public interface. Inside a method, call a setter as self.x = 1; plain x = 1 creates a local variable.

24. What is the difference between class variables and class instance variables?

@@count is shared between a class and all its subclasses, which causes surprising bugs when a subclass changes it. A class instance variable (@count set inside class << self or a class method) belongs to one class object and is not shared with subclasses. Prefer the latter, or a constant holding a mutable object. See Instance and Class Methods.

25. When do you choose Struct, Data or a class?

Struct makes a mutable record with accessors. Data.define makes an immutable value object with keyword or positional construction, with for copies and pattern matching support. Write a class when you need behavior, validation or hidden state. See Struct and Data.

Ruby Struct, Data and pattern matching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

26. What do you get by including Comparable and Enumerable?

Define <=> and include Comparable to get <, <=, ==, >, >=, between? and clamp. Define each and include Enumerable to get map, select, sort, min, reduce, first, include? and dozens of other methods. They are the two most useful mixins in the core library. See The Enumerable Module and Comparable.

27. What is the difference between dup and clone? Are they deep?

Both make shallow copies: nested objects are shared. clone also keeps the frozen state and singleton methods; dup does not. For a deep copy, write your own initialize_copy or use Marshal.load(Marshal.dump(obj)) for plain data. See Copying Objects.

Ruby Shallow versus deep copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

28. What is duck typing?

Ruby cares about what an object can do, not what class it has. If it responds to speak, you can call speak. Use respond_to? sparingly, because the best duck typing simply calls the method and documents the expectation. The alternative, checking is_a? everywhere, makes code rigid and hard to test. See Duck Typing and Polymorphism.

Errors and exceptions

29. What is the exception hierarchy, and why not rescue Exception?

Everything inherits from Exception. Ordinary program errors inherit from StandardError (including ArgumentError, TypeError, NameError, ZeroDivisionError, KeyError), and a bare rescue catches just those. Exception also covers SystemExit, Interrupt and NoMemoryError, so rescuing it makes the program impossible to stop. See Exceptions.

Ruby rescue, else, ensure and the hierarchy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

30. What do else, ensure and retry do in a begin block?

else runs only if nothing was raised. ensure always runs, whether or not an exception happened, and is the place to close files and release locks. retry inside a rescue clause restarts the begin block, which is handy for transient failures, but should have a counter so it cannot loop forever.

31. How do you write a custom exception, and what is cause?

Subclass StandardError, give it a clear name, and optionally override initialize to build a message. When you raise inside a rescue, Ruby stores the original exception in cause automatically, so wrapping errors keeps the history. See Custom Exceptions.

32. How are catch/throw different from raise/rescue?

catch and throw are a non-local jump for normal control flow, such as leaving deeply nested loops with a value. They do not create an exception object or a backtrace. Use them rarely; if you can put the search in a method and return, that is clearer. See catch and throw.

Metaprogramming

33. What is the difference between send and public_send?

Both call a method by name. send can call private methods; public_send respects visibility. Prefer public_send for names that come from outside, because send can be abused to reach internals.

34. What does define_method do compared with def?

def defines a method with fixed syntax, in a new scope. define_method(name) { ... } defines a method at runtime from a block, so the name can be computed and the body is a closure over the surrounding variables. It is the foundation for macros such as attr_accessor. See define_method and Dynamic Methods.

35. What are method_missing and respond_to_missing??

If lookup fails, Ruby calls method_missing(name, *args). You can answer dynamically (for example get_* helpers) and call super for everything else so the normal NoMethodError still appears. Always implement respond_to_missing? too, so respond_to? and method(:name) agree with your ghost methods. See method_missing and respond_to_missing?.

Ruby send, define_method and method_missing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

36. What is a singleton class?

Every object can have its own hidden class that holds methods defined just for it. def obj.hello and class << obj define methods there. Class methods are simply singleton methods of the class object, which is why def self.create works and why extend on a class adds class methods. See Singleton Methods and the Singleton Class.

37. What are refinements, and why are they safer than monkey patching?

A refinement changes a class only in the scope where you call using, instead of globally. That limits the damage of adding or replacing methods on core classes. Plain monkey patching affects every caller in the process, including gems. If you must reopen a class, prefer a refinement, or a prepended module that you can find in ancestors. See Refinements and Monkey Patching and Safe Alternatives.

38. What are hooks like inherited and included?

They are methods Ruby calls when something happens: inherited(subclass) when a class is subclassed, included(base) and extended(base) when a module is mixed in, method_added when a method is defined. Libraries use them to register subclasses or add class macros. See Hooks and Callbacks.

Concurrency

39. What is the GVL, and are Ruby threads useful?

The Global VM Lock lets only one thread run Ruby code at a time in CRuby. Threads still help for I/O-bound work (network calls, files, sleeping), because a thread waiting on I/O releases the lock. They do not speed up CPU-bound code. For CPU work, use processes (fork) or Ractors. The GVL does not make your code thread-safe: counter += 1 is still a race, so you protect shared state with a Mutex or a Queue. See Threads and Mutex, Queue and ConditionVariable.

Ruby Mutex, Queue and Thread#value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

40. How do Threads, Fibers and Ractors differ?

Threads are scheduled by the VM and can be preempted; they share memory, so they need locks. Fibers are cooperative: they run until they Fiber.yield, so they need no locks, and a fiber scheduler can switch fibers at I/O waits. Ractors are isolated actors that can run in parallel, because they do not share most objects and communicate by message passing; in Ruby 4.0 you read a Ractor's result with Ractor#value, and Ractor#take is gone. Ractors are still experimental, so many programs use processes for CPU parallelism. See Fibers, Ractors and Parallelism and Ractors.

How to prepare

Interviewers care less about the exact words than about whether you can reason. For each answer above, make sure you can do three things: give a one-sentence definition, show a short example, and name the pitfall. For performance questions, say what you would measure first. For design questions, say what you would test. And when you do not remember a detail, say how you would find out (Class.ancestors, method(:name).owner, p, the docs): that is the real skill.

Practice with the tools, not just the text. Take a question, close this page, write a ten-line program that demonstrates the answer, and run it. If the output surprises you, you have found a topic worth another look.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In class Dog < Animal; include Polite; prepend Loud; end, which module's method runs first?

    The ancestor chain is Loud, Dog, Polite, Animal, Object, and lookup walks it in order. Prepended modules sit in front of the class itself.
  2. 2. What is the main difference between a proc and a lambda?

    Lambdas are strict about arity and return from themselves. A proc is lenient with arguments and return leaves the enclosing method.
  3. 3. Why is rescue Exception a bad idea?

    Exception is the root class. A bare rescue (StandardError) is almost always what you want, or better, the specific class you can handle.
  4. 4. What does the GVL mean for CRuby threads?

    The GVL serializes Ruby code, but a thread blocked on I/O releases it. Race conditions are still possible, so shared state needs a Mutex.
  5. 5. Which copy is independent of the original for { tags: ["a"] }?

    dup and clone are shallow, so the nested array is shared. Marshal round-tripping creates new nested objects. Plain assignment copies nothing.

Summary

  • Know the basics cold: falsy values, strings versus symbols, the four equality operators, and that arguments are object references passed by value.
  • Blocks, procs and lambdas differ in arity checking and in what return does; closures keep their variables alive.
  • Method lookup follows ancestors: prepended modules, the class, included modules, then the superclass.
  • Prefer StandardError subclasses; ensure always runs, and cause keeps the history of wrapped errors.
  • Metaprogramming tools are send/public_send, define_method, method_missing with respond_to_missing?, singleton classes, hooks and refinements.
  • The GVL means threads help with I/O only; use a Mutex for shared state, and processes or Ractors for CPU parallelism.
  • Explain with a definition, an example and a pitfall, and say how you would check it in a console.

You have reached the end of the Ruby tutorial. Keep the cheat sheet nearby, build a small project of your own, and come back to any lesson from the Ruby tutorial index whenever you need a refresher.