Project

General

Profile

Bug #5288 » method_to_proc.rb

ernie (Ernie Miller), 09/07/2011 08:51 AM

 
1
#!/usr/bin/env ruby
2
# http://www.ruby-doc.org/core-1.8.7/classes/Object.html#M000006 :
3
#
4
# obj.instance_exec(arg...) {|var...| block } => obj
5
#
6
# Executes the given block within the context of the receiver (obj).
7
# In order to set the context, the variable self is set to obj while
8
# the code is executing, giving the code access to obj‘s instance variables.
9
# Arguments are passed as block parameters.
10

    
11
class Classy
12
  def self.foo
13
    puts self
14
  end
15

    
16
  def bar
17
    puts self
18
  end
19
end
20

    
21
class Executioner
22
  def exec(&block)
23
    instance_exec &block
24
  end
25
end
26

    
27
exe = Executioner.new # => #<Executioner:0x007f8cb884d108>
28

    
29
exe.exec { puts self } # => #<Executioner:0x007f8cb884d108>
30

    
31
exe.exec &lambda { puts self } # => #<Executioner:0x007f8cb884d108>
32

    
33
exe.exec &Classy.method(:foo).clone # => Classy
34

    
35
exe.exec &Classy.new.method(:bar).clone # => #<Classy:0x007f8cb884ce10>