LazyString
LazyString is a Ruby class for computing strings only when necessary. This is
useful when computing the string is expensive but the string is unlikely to be
used: an error message passed as an argument, for example.
Thanks to Ruby's duck typing and conversion protocols, you can often use an
instance of LazyString where you previously used an instance of String.
Usage
LazyString is packaged as a gem. Once you've installed it and required the
file, you can create a lazy string by sending new to LazyString with a block
argument. The block should return an object that converts to a string:
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 sent to the lazy string, the saved proc based
on your block will be called with no arguments and the returned object
converted to create the real string.
# String interpolation sends to_s.
s = "Lazy string computes this: #ls"
Once the string is computed, it will be saved, so sending to_str or to_s again
will not cause the computation to be performed again.
LazyString is a Ruby class for computing strings only when necessary. This is
useful when computing the string is expensive but the string is unlikely to be
used: an error message passed as an argument, for example.
Thanks to Ruby's duck typing and conversion protocols, you can often use an
instance of LazyString where you previously used an instance of String.
Usage
LazyString is packaged as a gem. Once you've installed it and required the
file, you can create a lazy string by sending new to LazyString with a block
argument. The block should return an object that converts to a string:
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 sent to the lazy string, the saved proc based
on your block will be called with no arguments and the returned object
converted to create the real string.
# String interpolation sends to_s.
s = "Lazy string computes this: #ls"
Once the string is computed, it will be saved, so sending to_str or to_s again
will not cause the computation to be performed again.