Twinkal Savani Twinkal Savani - 4 years ago 135
Ruby Question

What is use of ||= begin....end block in ruby?

what is difference in below two code snippet.

def config
@config ||= begin
if config_exists?
@config = return some value
else
{}
end
end
end


and

def config
@config ||= method
end

def method
if config_exists?
return some value
else
{}
end
end


Confused in "begin..end" block. Does it make any difference in output?
if NO, then what is use of begin..end block here!!!

Answer Source

First of all, you need to be aware that a defined method inherently includes the functionality of a begin ... end block.

In the context of exception handling, def method_name ... end is functionally equivalent to begin ... end. Both can include rescue statements for example.

The two blocks of code you have shared are actually identical, and there is no benefit in one over the other ... unless your method is needed in more than one place. In that case, you DRY up your code by putting the logic into a single method and calling it from multiple other places.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download