return_on

L

Logan Capaldo

Sometimes i do this:

return x if x

Anyway to code it as:

return_on x

t.
This is pure unadulterated evil, however it did come up in #ruby-lang a
while ago, so I whipped up some good old fashioned homemade evil:

def try_return(&block)
unless (blah = block.call).nil?
GC.disable
eval("return ObjectSpace._id2ref(#{blah.object_id})", block)
end
ensure
GC.enable
end

def f
try_return { nil }
try_return { 7 }
0
end

p f
 
R

Rob Sanheim

Simon said:
I cannot recall I ever have used return, in this way,
but my coding style may be 5% different than yours.
Maybe I can improve my minimal insight.

Any good (larger) examples of this thing?

I don't really have any examples that are repleat with it, but as to
insight it's especially convenient when caching a return value:

def x
return_on @cache[:x]
# do stuff
@cache[:x] = result_of_stuff
end

this gets rid of an extraneous variable too b/c otherwise, the more
efficient impl. is:

def x
r = @cache[:x]
return r if r
# do stuff
@cache[:x] = result_of_stuff
end

funny thing i just came across a similar case for break. how would you
DRY this up and get rid of 'result'?

result = nil
files.each do
result = require file
break if result
end
if result
...

t.

Much like returning in ActiveSupport:
http://weblog.jamisbuck.org/2006/10/27/mining-activesupport-object-returning

- rob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top