How can I test if a block is empty?
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 possibl开发者_如何学Ce?
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.
Update: Ruby 2.0+ removed block comparison, so it is no longer possible using only the builtin methods.
Ruby used to compare Proc
s, 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.
精彩评论