Multi-line Memoization in Ruby

During a recent code review, David pointed out a quick tip to do multi-line memoization. It's a cool technique that I've used in my own code:

class Search
  def results
    @results ||= begin
      response = Fleakr::Api::MethodRequest.with_response!('photos.search', parameters)
      (response.body/'rsp/photos/photo').map {|p| Photo.new(p) }
    end
  end
end

Check out the post on the Viget Extend blog for more details.

blog comments powered by Disqus