Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for "return x if x" in Ruby

Tags:

ruby

shorthand

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.

like image 235
Jonathan Allard Avatar asked May 29 '12 17:05

Jonathan Allard


People also ask

What does .first mean in Ruby?

The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.

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.

What is <% in Ruby?

Tags. ERB has two tags for Ruby code, a tag for comments, and a way to escape tag delimiters. <%= EXPRESSION %> — Inserts the value of an expression. With -%> — Trims the following line break.


1 Answers

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

like image 163
Matchu Avatar answered Sep 26 '22 06:09

Matchu