Module: Ruby::Enum::Case::ClassMethods

Defined in:
lib/ruby-enum/enum/case.rb

Overview

See Also:

Defined Under Namespace

Classes: NotAllCasesHandledError, ValuesNotDefinedError

Instance Method Summary collapse

Instance Method Details

#case(value, cases) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ruby-enum/enum/case.rb', line 44

def case(value, cases)
  validate_cases(cases)

  filtered_cases = cases.select do |values, _proc|
    values = [values] unless values.is_a?(Array)
    values.include?(value)
  end

  return call_proc(cases[:else], value) if filtered_cases.none?

  results = filtered_cases.map { |_values, proc| call_proc(proc, value) }

  # Return the first result if there is only one result
  results.size == 1 ? results.first : results
end