Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if a block is empty?

Tags:

ruby

lambda

block

I have a block of code and I'd like to test if the body is empty without running the code inside of the block. Is that possible?

like image 230
scrrr Avatar asked Aug 05 '11 12:08

scrrr


2 Answers

The sourcify gem adds a Proc#to_source method:

>> require 'sourcify'
=> true
>> p = Proc.new {}
=> #<Proc:0x000001028490b0@(irb):3>
>> p.to_source
=> "proc { }"

Once you have the block as a string it's fairly easy to see if there's noting (or only whitespace) between the curly braces.

like image 157
Michael Kohl Avatar answered Oct 08 '22 01:10

Michael Kohl


Update: Ruby 2.0+ removed block comparison, so it is no longer possible using only the builtin methods.

Ruby used to compare Procs, but was not great at it. For instance you could:

def is_trivial_block?(&block)
  block == Proc.new{}
end

is_trivial_block?{} # => true
is_trivial_block?{ 42 } # => false
# but caution:
is_trivial_block?{|foo|} # => false

Because of this, it was decided to remove the block comparison, so two blocks are now == iff they are the same object.

like image 36
Marc-André Lafortune Avatar answered Oct 08 '22 00:10

Marc-André Lafortune