Created
May 24, 2012 20:11
-
-
Save hypomodern/2783931 to your computer and use it in GitHub Desktop.
Blocks become of class Proc in a useful context ;)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Proc | |
def foobar | |
puts "...method on Proc!" | |
end | |
end | |
def block_class &block | |
block.call | |
block.foobar | |
puts block.class.inspect | |
end | |
block_class { puts "I'm a..." } | |
# I'm a... | |
# method on Proc! | |
# Proc | |
Try this instead:
def foo(&block)
block.class.name
end
foo { 1 } # => "Proc"
Of course, you can't just assign a block to a variable without a method. But if you have that method return the block, it is a Proc. So how are blocks not of class Proc?
blocks are of type rb_block_t while procs are an rb_proc_t, which, as you can see, contains an rb_block_t
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How is that any different than a method then? Note: I'm only investigating empirically :).
(def foo; end).class #=> NilClass
def block_class(&block)
puts block.inspect
end
block_class {}.class.inspect # => "NilClass"