Skip to content

Instantly share code, notes, and snippets.

@kaspergrubbe
Created July 29, 2013 16:43
Show Gist options
  • Select an option

  • Save kaspergrubbe/6105698 to your computer and use it in GitHub Desktop.

Select an option

Save kaspergrubbe/6105698 to your computer and use it in GitHub Desktop.
Ruby procs
class Worker
def hello(work)
work.call
end
def name(n)
"Worker #{n}"
end
end
class Master
def test
w = Worker.new
w.hello Proc.new {
puts name("Kasper")
}
end
end
m = Master.new
m.test
@kaspergrubbe
Copy link
Author

Gives this output:

ruby_proc.rb:15:in `block in test': undefined method `name' for #<Master:0x007fa39eff3ea0> (NoMethodError)
    from ruby_proc.rb:3:in `call'
    from ruby_proc.rb:3:in `hello'
    from ruby_proc.rb:14:in `test'
    from ruby_proc.rb:21:in `<main>'

@kaspergrubbe
Copy link
Author

This fixed my issue:

class Worker
  def hello(&block)
    instance_eval &block
  end

  def name(n)
    "Worker #{n}"
  end
end

class Master
  def test
    w = Worker.new
    w.hello { puts name("Kasper") }
  end
end

m = Master.new
m.test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment