Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 22 of 23 · Ruby 3.2

Scope a method extension with refinements

Activate an extension in a lexical scope.

Learn

Reopening a class changes methods for its users broadly. A refinement can limit where an extension is active. Define the extension inside refine, then activate the containing module with using.

Activation follows where code is defined, not simply which object is passed around. A method defined outside the active scope does not gain the refinement merely because a caller activated it. Keep this distinction in mind when splitting code into methods.

Example

module ExcitedText
  refine String do
    def excited
      self + "!"
    end
  end
end
using ExcitedText
puts "Ruby".excited

Experiment

  • Predict both the transformed strings and the original array. Change the method to add a question mark and compare whether the source strings change.

  • Predict both calls. Add using DecoratedText inside PlainView before its method definition and compare the behavior.

Explore the official manual

Ruby 3.2.4 · Example

Ready to run

Output

Run the code to see what happens.