Emma
Emma

Reputation: 13

How do I use a block as an expression in ruby

I essentially want to know what's the most idiomatic way to do this:

@var ||= lambda {
  #some expression here to generate @var
}.call

Upvotes: 1

Views: 122

Answers (1)

Thomas Klemm
Thomas Klemm

Reputation: 10856

You can use a multi-line block to achieve this kind of memoization.

@result ||= begin
   # The return value in here will be assigned to @result.
end

This syntax can be broken into two methods.

def result
  @result ||= generate_result
end

def generate_result
  # Do the heavy lifting here
end

Edit: These stackoverflow answers might help, too.

Upvotes: 1

Related Questions