Project

General

Profile

Actions

Feature #8452

open

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

Added by prijutme4ty (Ilya Vorontsov) over 11 years ago.

Status:
Open
Assignee:
-
Target version:
-
[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

No data to display

Actions

Also available in: Atom PDF

Like0