Shorthand for "return x if x" in Ruby
Asked Answered
S

2

11

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.

Stockmon answered 29/5, 2012 at 17:58 Comment(4)
What is wrong with replacing return x if x with simply x ?Karlotta
@Karlotta It is not necessarily the last statementStockmon
Maybe my math skills have deteriorated, but isn't what you have already a one-liner?Annuitant
Astute observation, @Jorg; I corrected it to "shorthand".Stockmon
R
4

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.)

Reforest answered 29/5, 2012 at 18:2 Comment(1)
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; ;)Stockmon
B
-1

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

example

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
Bashan answered 29/5, 2012 at 18:1 Comment(1)
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!Stockmon

© 2022 - 2024 — McMap. All rights reserved.