2

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

2 Answers 2

7

The lambda method is defined in the Kernel module. Object includes Kernel. BasicObject does not. So if you want to use lambda from 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 &block does the same thing as just writing @var1 = block, so the use of lambda isn't actually necessary here.

Sign up to request clarification or add additional context in comments.

8 Comments

what should I do to use lambda then?
@AlanDert I've expanded my answer.
@AlanDert Ah, sorry, my bad. ::Kernel then.
Note that @var1 = lambda &block does the same thing as just writing @var1 = block Can you please give a link where it's explained? I already ready about blocks, lambdas, proc and there was no information about it.
@AlanDert Where what's explained? Or asked differently: What do you expect @var1 = lambda &block to do differently than @var1 = block?
|
0

You are using BasicObject as base class which is an explicit Blank class and specifically does not include Kernel, so you need the qualifier ::Kernel when you access any Kernel method.

On a separate note -

Instead of passing an argument that you have a block you can use the Kernel method block_given? So taking your example -

class A
  def initialize  *args, &block
    if block_given?
      @var1 = lambda &block
    end
    puts @var1.call
  end
end
a = A.new  123  do |var|
  puts "ha ha ha"
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.