Take the 2-minute tour ×

One thing I love about Ruby is that you can express things in the shortest way possible.

I know that one can do, when assigning

x ||= a
# instead of
x = a unless x
# which is
x = x || a

Is there an analog form for return?

# instead of
return x if x

I'm trying to "say" x only once. This question asks about just returning (nothing), but I don't see how to do it when returning something other than void.

share|improve this question
What is wrong with replacing return x if x with simply x ? –  Zabba May 29 '12 at 18:17
@Zabba It is not necessarily the last statement –  Jonathan Allard May 29 '12 at 18:21
Maybe my math skills have deteriorated, but isn't what you have already a one-liner? –  Jörg W Mittag May 29 '12 at 18:35
Astute observation, @Jorg; I corrected it to "shorthand". –  Jonathan Allard May 30 '12 at 2:42

2 Answers 2

up vote 3 down vote accepted

I'm just about certain that there exists no shorthand for your second example—nor could one be written without modifying the Ruby syntax—since it's not a common enough idiom. Sorry, bro, but it looks like you're going to have to be verbose on this one. (Though, really, as far as verbosity goes, this one isn't all that bad.)

(Note, too, that the first example isn't quite right: x ||= a is equivalent to x = x || a, which can also be expressed as x = a unless x.)

share|improve this answer
You're right, I just corrected it. Since you're "just about certain", I'll wait a bit and admit this as the answer unless someone else has one. So answer = yours; answer ||= new_answer, or should I say return new_answer if new_answer; yours; ;) –  Jonathan Allard May 29 '12 at 18:15

you can omit the return if it is the last statement in a block code.


irb(main):002:0> def b(c)
irb(main):003:1>   c if c
irb(main):004:1> end
=> nil
irb(main):005:0> b(4)
=> 4
irb(main):006:0> b(nil)
=> nil
irb(main):007:0> b(true)
=> true
irb(main):008:0> b(false) # TADA!!!
=> nil
share|improve this answer
I can sure omit return if it's my last statement, but my intention was to say c only once. And in my case, I want to cover not-last statements too! –  Jonathan Allard May 29 '12 at 18:09

Your Answer


