Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for: return if not nil

Tags:

ruby

I use variable caching to cut down on execution time like so:

def some_method
  return @var if @var
  [some other code that gets executed only once]
end

Is there a shorthand for return @var if @var ? If its a single line method I use:

@var ||= [some more code]

Can something similar (short) be done with multiline methods?

like image 728
Severin Avatar asked May 12 '14 07:05

Severin


People also ask

How do you know if a ruby is nil?

In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).

What is return in Ruby?

Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.


1 Answers

I use this:

@var ||= begin
   # ...
end
like image 113
mdesantis Avatar answered Nov 03 '22 23:11

mdesantis