Project

General

Profile

Feature #8452

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

Added by Ilya Vorontsov almost 3 years ago.

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

Description

Imagine you have code like this
(long_computation_chain || []).do_smth
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:
long_computation_chain.otherwise([]).do_smth
or
long_computation_chain.otherwise('default', :empty?).do_smth
or
long_computation_chain.otherwise('numbers not allowed', ->(x){ x.grep(/\d+/) }).do_smth

Also available in: Atom PDF