Skip to content

Instantly share code, notes, and snippets.

@hypomodern
Created May 24, 2012 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hypomodern/2783931 to your computer and use it in GitHub Desktop.
Save hypomodern/2783931 to your computer and use it in GitHub Desktop.
Blocks become of class Proc in a useful context ;)
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
@steveklabnik
Copy link

Ruby cheats, actually. It's not a block after it gets passed into the block_class method... but as a block, it has no class.

@hypomodern
Copy link
Author

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"

@dplummer
Copy link

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?

@steveklabnik
Copy link

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