Reputation: 3758
I'm coding something in Ruby where, given a value foo
output from a method call, I want to:
foo
if foo
is truthyfoo
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.)
Upvotes: 5
Views: 364
Reputation: 110725
All things considered, I would go with:
foo = procedure(input)
return foo if foo
log_error
default
Upvotes: 0
Reputation: 3758
For the sake of completeness (and since no one has posted it yet) I'll add my original attempt at an answer:
procedure(input) || proc {
log_error
default
}.call
I can't think of any reason to use this over @mwp's answer:
procedure(input) || begin
log_error
default
end
because of the extra overhead (performance and readability) involved in creating the Proc object. Though some quick benchmarking reveals that the performance difference should be negligible in most cases, since the Proc object doesn't seem to be created unless procedure(input)
is falsy.
Upvotes: 0
Reputation: 8467
This is a rare case where Ruby's anonymous block is actually useful:
foo = procedure(input) || begin
log_error
default
end
Upvotes: 4
Reputation: 10951
You can write that if log_error
returns a true value
foo || log_error && default
If not:
foo || (log_error; default)
Upvotes: 2
Reputation: 369526
Living off of Ruby's Perl heritage:
foo = procedure(input) and return foo
log_error
default
Upvotes: 4