开发者

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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜