Search code examples
rubybindingblock

Binding within a block


I'd like to use a block within method initialize. With this code:

class Settlement
  attr_reader :url, :parameters
  def initialize(&block)
    instance_eval block.call
  end
  def parameters(x) ; @parameters = x; end
  def url(x) ; @url = x;  end
end

settlement = Settlement.new do
  url "https://xxxxx"
  parameters("ffff")
end

I got the error message below:

NoMethodError - undefined method parameters

Any ideas?


Solution

  • When you call instance_eval block.call block.call is evaluated before instance_eval is called. This means the block is called without the instance binding.

    This should work:

    def initialize(&block)
      instance_eval &block
    end