rubylambdasingletoncodeblocksinstance-eval

Ruby: Properly using Lambdas


Before I start, I have tried fiddling with instance_eval and singleton methods to no avail. I am going to present my "best" attempt at the problem.

I am trying to do the following:

value = rule(condition: lambda {@something > 100})
value.act(120)

The above calls cannot change.

What can change is how rule is defined:

def rule(condition: nil)
    t = Object.new
    t.class.module_eval{
        attr_accessor :condition       

        def act(something)
            if(condition.call(something))
                return "SUCCESS"
            end
        end
    }
    t.condition = condition
    return t
end

I am unsure how to get the lambda code block to get the value of something. Any help or point in the right direction would be appreciated!


Solution

  • If these calls can not change:

    value = rule(condition: lambda {@something > 100})
    value.act(120)
    

    Try instance_exec:

    def rule(condition: nil)
      t = Object.new
      t.class.module_eval do
        attr_accessor :condition       
    
        def act(something)
          @something = something
    
          if(instance_exec &condition)
             "SUCCESS"
          else
            "FAILURE"
          end
        end
      end
      t.condition = condition
      t
    end
    

    It invokes the condition in t's context.