Skip to content
Tutorials Center
My learning

Topics

Lesson 134 of 134 ยท Practice

Practice Problems: OOP and Metaprogramming

Seven Ruby exercises on classes, Comparable, Enumerable, class-level macros, method_missing proxies, instance_eval DSLs and prepend, each with a hint and a tested solution.

Object-oriented design and metaprogramming are where Ruby interviews, and real code reviews, get interesting. Anyone can write a class with getters. The harder questions are: can you make your own collection behave like an array, can you write a validates-style macro, and can you wrap a method without touching its source? This lesson gives you seven exercises that grow in difficulty, each with a statement, a hint and a runnable solution.

As with the array, string and hash problems, try each one yourself first. The solutions are compact on purpose. Pay attention to why each design works: which module is included, where a method is defined, and what the receiver (self) is at that moment.

Problem 1: A money value object

Task. Write a Money class that stores whole cents and a currency code. It must support + and - with another Money of the same currency (and raise ArgumentError for mixed currencies), comparison with <, >, == and sort, a readable to_s such as USD 12.50, and it must work as a hash key.

Hint. Include Comparable and define <=>. A value object is immutable, so freeze it. For hash-key behavior define eql? and hash together. See Comparable and Equality and Identity.

Ruby Money value object

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.

== comes free from Comparable and uses <=>, while eql? and hash are what Hash uses; they must agree, so both read the same state. Marking state as protected lets one Money read another's state without exposing it to the world. Compare the two visibility keywords in Visibility.

Problem 2: A collection that behaves like an array

Task. Build a LinkedList with push, each, and size. After you add only those, it should answer map, select, include?, first(n), sort, min and to_a without you writing them.

Hint. include Enumerable and define each that yields every element and returns an enumerator when called without a block. Everything else is built on that single method. See Enumerable and Enumerators.

Ruby Enumerable linked list

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.

Returning to_enum(:each) { size } is the idiom that makes list.each without a block work and lets each.size answer without walking the list. Because each returns self after finishing, it follows the convention of the built-in each.

Problems 3 and 4: Class-level macros

Problem 3: validates. Write a small module Validations so a class can say validates :name, presence: true and validates :age, range: 0..130, then call valid? and read errors.

Problem 4: attr_with_history. Add a class macro attr_with_history :score that defines a reader, a writer and a score_history method listing every value the attribute has held, including nil at the start.

Hint. Both are class methods that store data on the class and generate or consult instance methods. For problem 3, use self.included(base) with base.extend(ClassMethods); for problem 4, define_method and instance_variable_get/instance_variable_set. See Hooks, define_method and Reflection.

Ruby validates and attr_with_history

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.

Reopening Module to add attr_with_history makes it available in every class, just like the built-in attr_accessor. That is convenient in an exercise and is monkey patching in real code, so in a production codebase you would put it in a module that classes extend. bad.errors lists both rules because valid? clears and refills the array on every call.

Problem 5: A logging proxy with method_missing

Task. Write LoggingProxy.new(target) that forwards every method call to the target, records the call (name and arguments) in a log, and still answers respond_to? correctly.

Hint. Define method_missing to log and forward the call with public_send, and respond_to_missing? so respond_to? agrees. See method_missing and forwardable-delegate.

Ruby Logging proxy

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.

Calling super in method_missing for names the target does not know turns an unknown call into the normal NoMethodError rather than silently swallowing typos. Note that methods already defined on every Object, such as to_s, inspect and ==, never reach method_missing; the proxy answers them itself. That is the main weakness of this approach and the reason BasicObject or Delegator exist.

Problem 6: A small DSL with instance_eval

Task. Write an html builder so that this reads naturally and returns a string:

Ruby
html do
  div class: "card" do
    h1 "Hello"
    p_ "Welcome"
  end
end

Hint. The block must run with self set to the builder, so div and h1 become method calls on it. instance_eval does that. Use method_missing to turn any name into a tag, and track the nesting depth to indent the output. See instance_eval and DSLs.

Ruby HTML builder DSL

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.

p_ ends in an underscore because p is already a method on Object (it prints), so it would never reach method_missing. Real builders such as Markaby or Builder solve this by inheriting from BasicObject. Remember also that instance variables of the caller are not visible inside an instance_eval block, because self changes. That is the classic DSL trade-off.

Problem 7: Wrapping a method with prepend

Task. Write a Memoize module so any class can say memoize :slow_square and get cached results without changing the method's body. Count how many times the real method runs.

Hint. Method lookup checks modules that were prepended before the class's own methods. Build an anonymous module with define_method that checks a cache and otherwise calls super, then prepend it.

flowchart LR
  call["calc.slow_square(4)"] --> mod["Memoized module<br/>(prepended)"]
  mod -- "cache miss: super" --> cls["Calculator#slow_square"]
  cls --> mod
  mod -- "cache hit: return" --> call

A prepended module sits in front of the class in the lookup chain, so it can run code before and after the original method.

Ruby memoize with 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.

return inside a define_method block returns from that generated method, since the block becomes a method body. The memo lives on the instance, so two calculators never share a cache. A real implementation would also forward keyword arguments and blocks (*args, **kwargs, &block), and might use Module#prepend with a named constant to make stack traces easier to read.

Habits to practice

  • Say where a method lives. Whenever you add behavior, explain whether it belongs on the instance, the class (a singleton method) or a module, and why.
  • Prefer modules to deep inheritance. Comparable and Enumerable give you dozens of methods for one required method; see Modules and Mixins and Inheritance.
  • Pair method_missing with respond_to_missing? and call super for unknown names.
  • Reach for define_method before eval. It is safer and keeps closures working. See eval and binding.
  • Keep magic discoverable. If your macro generates methods, name them predictably and document them. Metaprogramming that nobody can grep for becomes a liability.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which single method must a class define after include Enumerable to get map, select and sort?

    Enumerable builds all of its methods on each. (Comparable, by contrast, needs <=>.)
  2. 2. Why must a hash-key class define both eql? and hash?

    Two objects that are eql? must return the same hash value, otherwise the hash looks in the wrong bucket and does not find equal keys.
  3. 3. In the HTML builder, why is the paragraph tag written p_ instead of p?

    method_missing only runs when no method is found. Kernel#p exists, so calling p would print instead of building a tag.
  4. 4. What does prepending a module change about method lookup?

    ancestors lists prepended modules first. When the prepended method calls super it reaches the class's own method.
  5. 5. What should method_missing do for a name the target does not support?

    Calling super preserves the normal error and keeps typos visible. Swallowing them hides bugs.

Summary

  • A value object is immutable, compares by value (Comparable plus eql? and hash) and rejects mixing incompatible units.
  • Write each and include Enumerable to give your collection dozens of methods; return to_enum when no block is given.
  • Class-level macros are class methods that store configuration on the class (validates) or generate methods with define_method (attr_with_history).
  • method_missing powers proxies and builders; always add respond_to_missing? and call super for unknown names.
  • instance_eval changes self for a block, which is how DSLs read like a language; the cost is losing the caller's instance variables.
  • prepend lets a module wrap a method and call super, a clean way to add caching, logging or timing without editing the original.

Next: Ruby Cheat Sheet