Codectionary / Developer documentation / Ruby

Lexically Scoped Refinements

Refinements extend methods within the lexical scope where using activates them. They provide an alternative to globally changing a core class. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

module Extension; refine String do ... end; end; using Extension

Examples

Lexically Scoped Refinements

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

module BracketedText
  refine String do
    def bracketed
      "[#{self}]"
    end
  end
end
using BracketedText
puts "hello".bracketed
  1. Expected output: [hello]
  2. The refinement adds bracketed for calls in the activated lexical scope. It does not globally install String#bracketed for unrelated files.

Best practices

  • Activate using at top level or within a class/module body, not inside a method.
  • Prefer ordinary helper methods when lexical method lookup would surprise maintainers.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading