Ruby is the cleanest way to return a value if it is true, or execute arbitrary code

I am coding something in Ruby where, when a value foois inferred from a method call, I want:

  • Returns fooif footrue
  • Record the error and return the default if foofalse.

The easiest naive way to implement this is probably:

foo = procedure(input)

if foo
  foo
else
  log_error
  default
end

but it’s too complicated because it is foorepeated three times, and this style is very necessary.

What is the cleanest, most idiomatic way to write this?

(Performance issues - let's say that foois true in the vast majority of cases.)

+4
5

Ruby Perl:

foo = procedure(input) and return foo
log_error
default
+5

, Ruby :

foo = procedure(input) || begin
  log_error
  default
end
+3

, log_error

foo || log_error && default

:

foo || (log_error; default)
+2

( ), :

procedure(input) || proc {
  log_error
  default
}.call

- @mwp:

procedure(input) || begin
  log_error
  default
end

- ( ), Proc. , , Proc , procedure(input) .

0

:

foo = procedure(input)
return foo if foo
log_error
default
0

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


All Articles