LazyString

LazyString is a Ruby 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.

Thanks to duck typing and Ruby's standard conversion protocols, you can pass
an instance of LazyString to many methods that ask for a string.


Usage

LazyString is packaged as a RubyGem. Once you've installed it and required the
file, you can create a lazy string by passing a block to LazyString.new:

ls = LazyString.new { "answer = #expensive_computation" }

The block (and therefore expensive_computation) will not be called immediately.
But later, if #to_str or #to_s is called on the lazy string, the block will be
called with no arguments in order to create the real string.

# String interpolation calls #to_s automatically.
s = "Lazy string computes this: #ls"

Once the string is computed, it will be saved, so any future invocations of
#to_str or #to_s will not perform the computation again.


Compatibility

This works on version 1.8.7 and later of Matz's Ruby Interpreter. (At the time
of this writing, 2.2.3 is the current version.)


Author

This software was written by Aaron Beckerman.


License

This software is distributed under the MIT License (also known as the Expat
License). See the LICENSE.txt file for details.