Feature #8452

Kernel#otherwise to rewrite code like (obj || default_obj).do_smth

Added by Ilya Vorontsov 11 months ago.

[ruby-core:55166]
Status:Open
Priority:Normal
Assignee:-
Category:-
Target version:-

Description

Imagine you have code like this
(longcomputationchain || []).dosmth
While it isn't difficult, but it forces a developer to use additional parentheses. It can be difficult to trace where opening bracket is when computation
chain is long. Due to this idiom code cannot be read or written left to right. This is the same problem as for
Hash[ *long_computation ]

So I propose a simple method Kernel#otherwise

def otherwise(value, check = nil)
  if !check
    self || value
  else
    check.to_proc.call(self) ? self : value
  end
end

So now one can write:
longcomputationchain.otherwise([]).dosmth
or
long
computationchain.otherwise('default', :empty?).dosmth
or
longcomputationchain.otherwise('numbers not allowed', ->(x){ x.grep(/\d+/) }).do_smth

Also available in: Atom PDF