Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
A Ruby class for a lazily-computed string.
Ruby
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
test
LICENSE.txt
README.txt
lazy_string.gemspec

README.txt

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 versions 1.8.6, 1.8.7, 1.9.2, and 1.9.3 of Matz's Ruby
Interpreter. (At the time of this writing, 1.9.3 is the current version.)


Author

This software was written by Aaron Beckerman, who you can email at
aaron@aaronbeckerman.com.


License

This software is distributed under the MIT License (also known as the Expat
License). See the LICENSE.txt file for details.
Something went wrong with that request. Please try again.