Class: LazyString

Inherits:
Object
  • Object
show all
Defined in:
lib/lazy_string.rb

Overview

A class for computing strings only when necessary.

Instance Method Summary collapse

Constructor Details

#initialize(&prc) ⇒ LazyString

Creates a new lazy string. It saves the block argument as a proc for later use by #to_str. If no block argument is given, it saves a proc that returns an empty string.



11
12
13
14
# File 'lib/lazy_string.rb', line 11

def initialize(&prc)
  @prc = prc || lambda { "" }
  nil
end

Instance Method Details

#to_sObject

Computes the string if necessary and returns it. It delegates to #to_str.



19
20
21
# File 'lib/lazy_string.rb', line 19

def to_s
  to_str
end

#to_strObject

Computes the string if necessary and returns it. It computes the string by calling, with no arguments, the saved proc based on the block argument passed to ::new. If the returned object responds to the to_str message, it sends to_str to that object to obtain the string; otherwise, it sends to_s. It saves the computed string, so subsequent invocations of this method will not recompute the string.



31
32
33
34
35
36
37
38
39
40
# File 'lib/lazy_string.rb', line 31

def to_str
  @str ||= begin
    result = @prc.call
    if result.respond_to?(:to_str)
      result.to_str
    else
      result.to_s
    end
  end
end