class LazyString

LazyString is a class for computing strings only when necessary – that is, when to_str or to_s is called. This is useful when computing the string is expensive, but the string is unlikely to be used: an error message passed as a method argument, for example.

Constants

VERSION

The version string.

Public Class Methods

new(&block) click to toggle source

Creates a new lazy string. The block argument will be saved for later use by to_str. If no block argument is given, it will default to a block that returns an empty string.

# File lib/lazy_string.rb, line 18
def initialize(&block)
  @block = block || lambda { '' }
end

Public Instance Methods

to_s() click to toggle source

A synonym for to_str.

# File lib/lazy_string.rb, line 25
def to_s
  to_str
end
to_str() click to toggle source

Returns the computed string. It will compute the string by calling (with no arguments) the block passed to ::new. If the block's return value responds to the to_str message, to_str will be called on it to create the string. Otherwise, to_s will be called on it. The computed string will be saved, so subsequent calls of this method will not cause the block to be called again.

# File lib/lazy_string.rb, line 37
def to_str
  @str ||= begin
    result = @block.call
    if result.respond_to?(:to_str)
      result.to_str
    else
      result.to_s
    end
  end
end