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.
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.
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.
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.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With