I have a code
class A < BasicObject
def initialize var1, *args, &block
if var1 == :lambda
@var1 = lambda &block
end
end
end
a = A.new :lambda, 123 do |var|
puts "ha ha ha"
end
why does it cause an error?
undefined method `lambda' for #<A:0x00000001687968> (NoMethodError)
unlike this one (it doesn’t cause it)
class A
def initialize var1, *args, &block
if var1 == :lambda
@var1 = lambda &block
end
end
end
The
lambdamethod is defined in theKernelmodule.ObjectincludesKernel.BasicObjectdoes not. So if you want to uselambdafrom a BasicObject, you have to call it as::Kernel.lambda.Note that this is not specific to
lambda– it applies to any other Kernel method (like e.g.puts) as well.PS: Note that
@var1 = lambda &blockdoes the same thing as just writing@var1 = block, so the use oflambdaisn’t actually necessary here.