Module: EmanLib

Defined in:
lib/emanlib.rb,
lib/patch/enum.rb

Defined Under Namespace

Modules: Enum

Class Method Summary collapse

Class Method Details

.let(*args, &block) ⇒ Object

Helper method to create definitions. A convenient shorthand for ‘Object.new.define(…)`.

Examples:

person = let(name: "Rio", age: 37)
puts person.name # => "Rio"
puts person.age  # => 37

point = let **{x: 10, y: 20}
puts point.x # => 10

settings = let do
  theme = "dark"
  font_size = 12
  binding
end
puts settings.theme # => "dark"

complex_data = let([[:id, 42]], name: "Xed") do
  details = { color: "red", size: "large" }
  binding # Required
end

puts complex_data.id            # => 42
puts complex_data.name          # => "Xed"
puts complex_data.details.color # => "red"

Parameters:

  • args (Array<Hash, Array>)

    A list of Hashes or “hashy” Arrays.

  • block (Proc)

    If provided, its local variables are used to define methods.

Returns:

  • (Object)

    A new object with dynamically defined methods.

See Also:

  • [Object[Object#define]


47
48
49
# File 'lib/emanlib.rb', line 47

def let(*args, &block)
  Object.new.define(*args, &block)
end

.support_lambdaObject

Support for using a ‘_` as the second operand with operators. WARN: This method WILL MODIFY the standard library classes. In particular, the operators: `- * / % ** & | ^ << >> <=> == === != > < >= <=` in the classes: `Integer, Float, Rational, Complex, Array, String, Hash, Range, Set`



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/emanlib.rb', line 55

def support_lambda
  [[Integer, Float, Rational, Complex, Array, String, Hash, Range, Set],
   %i[- * / % ** & | ^ << >> <=> == === != > < >= <=]].op(:product)
    .each do |klass, op|
    next unless klass.instance_methods(false).include?(op)

    original = klass.instance_method(op)
    klass.define_method(op) do |other|
      if other.is_a?(Lambda)
        repr = [self]
        repr.concat(other.repr)
        repr << Lambda::Function.new(op)
        Lambda.new(repr)
      else
        original.bind(self).call(other)
      end
    end
  end
end