maskedXchaotic
maskedXchaotic

Reputation: 101

How to call Class methods in block?

class ShoppingList
  def add(a,b)
    print a,b
  end
  def items(&block)
    block.call
  end
end

s1 = ShoppingList.new
s1.add(4,10)
s1.items do 
  add(5,2)
end

undefined method `add' for main:Object

(repl):19:in `block in '

(repl):12:in `items'

how to call add in block ?..

Upvotes: 0

Views: 502

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51151

If you want to call block in the context of the items message recipient, you can use instance_eval:

def items(&block)
  instance_eval(&block)
end

Upvotes: 4

Related Questions