Abbreviation for "return x if x" in Ruby

One thing that I love about Ruby is that you can express things as short as possible.

I know that this can be done at the appointment

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 try to "say" x only once. This question asks for a return (nothing), but I don’t see how to do this, returning something other than void.

+6
source share
2 answers

I am pretty sure that there is no transcript for your second example, and cannot be written without changing the Ruby syntax, as this is not a common idiom. Sorry brother, but it looks like you have to be detailed on this. (Although, indeed, as far as verbosity goes, it's not so bad.)

(We also note that the first example is not quite right: x ||= a equivalent to x = x || a , which can also be expressed as x = a unless x .)

+4
source

you can omit the return if this is the last statement in the 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 
-1
source

Source: https://habr.com/ru/post/916931/


All Articles