Ignore lambda argument checking

I want to convert a proc that shows lambda behavior (argument checking) to one that doesn't. The following is a very far-fetched example, but it should get the point:

The goal is to create a DSL that looks something like this:

NumberSeries.perform do
  add first_series:  -> { natural_numbers.take(10) },
      second_series: -> { fibonacci_numbers.take(10) }
end

Note that natural_numbersand fibonacci_numbersare not passed as arguments to the DSL. The implementation addlooks something like this:

NaturalNumbersFibonacciNumbers = Struct.new(:natural_numbers, :fibonacci_numbers)
FAMOUS_NUMBER_SERIES = NaturalNumbersFibonacciNumbers.
                         new(natural_numbers, fibonacci_numbers)

def add(first_series:, second_series:)
  first_numbers  = FAMOUS_NUMBER_SERIES.instance_eval(&first_series)
  second_numbers = FAMOUS_NUMBER_SERIES.instance_eval(&second_series)
  first_numbers.zip(second_numbers).map { |x, y| x + y }
end

Now, if I replaced ->with procin the DSL, it will work. However, keeping lambdas, I would get

ArgumentError: wrong number of arguments (1 to 0)

as BasicObject#instance_evalgives self for lambda, but lambda does not expect arguments.


I do not want to use Fiddlefor obvious reasons.

+4
1

instance_exec instance_eval, , , instance_eval . , :

irb:108:0>  Object.new.instance_eval &-> { puts "Hello" }
ArgumentError: wrong number of arguments (given 1, expected 0)
    from (irb):108:in `block in irb_binding'
    from (irb):108:in `instance_eval'
    from (irb):108
    from /Users/matt/.rubies/ruby-2.3.0/bin/irb:11:in `<main>'
irb:109:0>  Object.new.instance_exec &-> { puts "Hello" }
Hello
=> nil
+1

All Articles