Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 134 ยท Methods and Blocks

Refinements

Learn Ruby refinements - refine and using, file and class scope, super inside a refinement, import_methods, and when refinements beat monkey patching.

Ruby lets you reopen any class, even String or Integer, and add methods to it. That is powerful and also dangerous: the new method is visible to every line of code in the program, including gems you did not write. If two libraries add a method with the same name to String, one silently wins. This habit is called monkey patching, and it is the reason experienced Rubyists treat core-class changes with suspicion (see Monkey Patching and Safe Alternatives).

Refinements are Ruby's answer. A refinement changes a class only inside a region of code that asks for it. Everything outside that region sees the original class. You get the convenience of 5.minutes or "hello".shout without touching the rest of the program. In this lesson you will learn how to define a refinement with refine, turn it on with using, where its scope begins and ends, how super works inside it, and where refinements stop working.

Defining and activating a refinement

A refinement lives inside a module. Inside the module you call refine ClassName do ... end and define methods in the block. Nothing happens yet: the methods exist but are inactive. The call using ModuleName activates them for the code that follows.

Ruby refine and using

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.

Before using, the call fails with undefined method 'shout' for an instance of String. After using Shout, the same call works. Notice that the activation is textual: it affects code written below the using line in the same file, not code that happens to run later. That is what makes refinements predictable. You can read a file from top to bottom and know exactly which methods exist at each line.

Ruby has worked hard to make refinements feel natural. The symbol-to-proc shortcut (map(&:shout)), send and string interpolation all honor an active refinement.

Refinements are a core feature and need no require. They have been stable since Ruby 2.0 (experimental) and 2.4 (mostly complete), so they are safe to use in any modern code base.

Scope: where a refinement is visible

A using call is valid in two places: at the top level of a file, or inside the body of a class or module. It is an error inside a method. The refinement then stays active until the end of that file or that class body.

Ruby using is lexically scoped

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.

Four things happen here, and each one teaches a rule:

  1. Inside class Headline, using Titles makes title_case available to the methods in that class body only.
  2. The very next line, outside the class, still sees the plain String, so the call fails.
  3. Once using Titles appears at the top level, everything below it is refined. The method before_using was written above that line, so it keeps failing even though it is called after the activation. The scope is where the code sits in the file, not when it runs.
  4. Calling using from inside a method raises RuntimeError with the message main.using is permitted only at toplevel.

This is the big difference from monkey patching. A monkey patch is global and takes effect at runtime. A refinement is local and takes effect at a position in the source text.

Refinements and super

Inside a refined method, super calls the original, unrefined version. That lets you wrap or adjust existing behavior without losing it.

Ruby Calling the original with super

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.

You can override existing methods, not just add new ones. The refinement of first wraps the original and super fetches the real answer, 10. Methods you did not refine, such as last, behave as usual.

Refining methods that other code relies on can be confusing, even when the scope is limited. Changing what Integer#to_s returns inside your file is legal, but a reader who sees 5.to_s will not suspect it. Prefer new, clearly named methods (minutes, title_case) over changing the meaning of old ones.

A realistic example: time units for Integer

A classic use case is a small vocabulary that reads well but should not pollute the global namespace.

Ruby Readable durations without global changes

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.

The Report module can write 90.minutes; any other code in the program cannot. Another library that defines its own Integer#minutes (returning a Duration object, say) would not clash with it, because each file chooses its own refinements.

Sharing code with import_methods

Sometimes you already have a normal module whose methods you want to become part of a refinement. Inside a refine block, import_methods copies the methods of a module into the refinement. The module must only contain Ruby-defined methods (not methods written in C).

Ruby import_methods

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.

The last line prints false. The methods exist only through the refinement, so asking the class itself does not find them. This is a tiny example of the main limitation, which the next section explores.

Limits and surprises

Refinements are deliberately restricted. Know these before you reach for them:

  • They do not show up in reflection the way normal methods do. Integer.method_defined?(:double) is false. Tools that inspect classes, such as serializers or documentation generators, will not see refined methods.
  • Dynamic features see them only sometimes. send, public_send, &:symbol and interpolation honor refinements. Code that lives in another file and calls your object does not.
  • They are invisible to code outside the scope. If you pass "text" to a library, the library cannot call title_case on it, because the library's source never said using Titles.
  • using cannot be undone. There is no unusing. Keep refinement scopes small by activating them inside a class or module body when you can.
  • They add a lookup step. Method calls inside a refined scope may be slightly slower to resolve. The cost is small for application code but worth knowing for hot loops.
Ruby Libraries do not see your refinement

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.

Library was written (above using) in a scope where cheer is not active, so its call fails even though the object came from refined code. The refined behavior belongs to the call site, not to the string.

When to use refinements

Reach for a refinement when you want to extend a core class in a way that is useful in your own file or module and harmful if everyone could see it. Good examples are small domain vocabularies, test helpers, and gems that want to offer optional sugar (using MyGem::Sugar).

Avoid them when behavior must be visible to frameworks (for example, anything Rails or a JSON serializer needs to call), when a plain helper method or a small wrapper class would do, or when the team is not familiar with the feature. A method such as Duration.minutes(5) is often clearer than a refined 5.minutes, and it needs no special rules.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line activates a refinement defined in module Shout?

    using Shout turns the refinement on for the rest of the file or class body. include and extend add ordinary module methods, and refine is used inside the module to define the refinement.
  2. 2. A method is defined at line 10 of a file and using Titles appears at line 20. The method is called at line 30 and uses a refined method. What happens?

    Refinements are lexically scoped. Code written above the using line never sees the refinement, no matter when it runs.
  3. 3. What does super do inside a refined method?

    super inside a refinement reaches the original method of the class being refined, so you can wrap existing behavior.
  4. 4. Where is using allowed?

    using inside a method raises RuntimeError (main.using is permitted only at toplevel for the main object). It belongs at the top level or in a class or module body.
  5. 5. Why might a refinement be a better choice than a monkey patch?

    A monkey patch is global. A refinement is visible only in the scope that calls using, which protects other libraries and the rest of the program.

Summary

  • A refinement is defined with refine SomeClass do ... end inside a module and activated with using.
  • Activation is lexical: it covers the code below the using line in the same file or class body, never code written above it or in other files.
  • using is allowed at the top level and in class or module bodies, not in methods.
  • Inside a refined method, super calls the original method.
  • import_methods copies the methods of an ordinary module into a refinement.
  • Refined methods are hidden from reflection such as method_defined?, and libraries cannot call them.
  • Use refinements for small, local vocabularies; prefer plain helper objects when behavior must be visible everywhere.

Next: Recursion