Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - cleanest way to return a value if truthy, or execute arbitrary code

I'm coding something in Ruby where, given a value foo output from a method call, I want to:

  • Return foo if foo is truthy
  • Log an error and return a default value if foo is falsy.

The simplest naive way to implement this is probably:

foo = procedure(input)

if foo
  foo
else
  log_error
  default
end

but this feels overly verbose because foo is repeated three times, and this style is very imperative.

What's the cleanest, most idiomatic way to write this?

(Performance matters-- let's assume that foo is truthy in the vast majority of cases.)

like image 365
Max Wallace Avatar asked Jan 08 '23 07:01

Max Wallace


1 Answers

Living off of Ruby's Perl heritage:

foo = procedure(input) and return foo
log_error
default
like image 153
Jörg W Mittag Avatar answered Jan 19 '23 07:01

Jörg W Mittag