Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to create a lambda that will return a stub class. This is what I've got:

engine_stub = lambda { |valid|
  Class.new {
    def valid?(address)
      valid
    end
  }
}

The lambda should return a class whose valid? instance method always returns the value passed to the lambda. This code fails with the error:

NameError: undefined local variable or method `valid' for #<#<Class:0x007f4bf0ebd
0f0>:0x007f4bf0ebcd08>

So clearly the method doesn't have access to the lambda scope. I also tried this:

engine_stub = lambda { |valid|
  stub_class = Class.new
  def stub_class.valid?(address)
    valid
  end
  return stub_class
}

Which instead causes this error:

NoMethodError: undefined method `valid?' for #<#<Class:0x007fecbada1138>:0x007fec
bada0df0>

So now I've failed to make valid? an instance variable.

Summary

I'm trying to get the lambda engine_stub to return a class with one instance method valid? that returns the value passed to the lambda. How do I do this?

share

2 Answers

The keyword def is a scope gate, so you should define method via define_method{}

 engine_stub = lambda { |valid|
    Class.new do
      class << self
        define_method(:valid?) do
          valid
        end
      end
     }
   } 
share

You need to use class_eval or similar to bring value in scope.

share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.