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 as a proc for later use by #to_str. If no block 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 || ::Proc.new { "" }
  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 representing the block passed to ::new. If an object is returned, this method converts it to a string and returns the result. It converts the object to a string by sending to_str to the object if it responds to that message and to_s otherwise. It saves the computed string, so subsequent invocations of this method will not recompute the string. If an exception is raised, this method immediately raises that exception and does not save any result.



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/lazy_string.rb', line 33

def to_str
  if defined? @str
    @str
  else
    result = @prc.call
    @str = if result.respond_to? :to_str
      result.to_str
    else
      result.to_s
    end
  end
end