From: Justin Collins Date: 2006-08-17T02:03:01+09:00 Subject: Re: block equality Tom Jordan wrote: > On 8/15/06, Justin Collins wrote: >> >> >> Marshall T. Vandegrift wrote: >> > "Tom Jordan" writes: >> > >> > >> >> Is there a way to compare two blocks with each other? >> >> >> >> If you promote a block into a Proc, how would you know that the >> >> original block was the same? >> >> >> > >> > I haven't dived into the code, but I'm pretty sure that (a) promoting >> > a block to a Proc via &block in the argument list results in a new >> > Proc each time and (b) ruby 1.8 provides no introspection into the >> > actual contents of a block. >> > >> > >> >> >> Yes, it's kind of like asking if two equations or two methods are equal. >> On the other hand, you could probably use the SerializeableProc >> (developed here: http://rubyquiz.com/quiz38.html), add an equality >> method, and then you'd have it. :) > > Thanks Marshall and Justin. > > This http://ruby-doc.org/core/classes/Proc.html#M001161 > > "Return true if prc is the same object as other_proc, or if they are > both procs with the same body." > > led me to believe that Procs would evaluate to equality if they had > the same body. > > So I would have expected that the following: > > s = lambda { x = 1 } > t = lambda { x = 1 } > s == t # => true expected, false in reality > > So my question is; when would the body of Procs ever be the same? > > Thanks, > -- Tom. Hi Tom, Well, I did find one instance where this works. If you use Proc#dup or Proc#clone, you will end up with a new Proc object, but they will evaluate to being equal: irb(main):001:0> a = Proc.new { n = 1 } => # irb(main):002:0> b = a.dup => # irb(main):003:0> a.object_id => -605441814 irb(main):004:0> b.object_id => -605445814 irb(main):005:0> a == b => true irb(main):006:0> b == a => true irb(main):007:0> c = Proc.new { n = 1 } => # irb(main):008:0> d = c.clone => # irb(main):009:0> c.object_id => -605470914 irb(main):010:0> d.object_id => -605475424 irb(main):011:0> c == d => true irb(main):012:0> d == c => true Other than that, I don't see a way for two Procs to have the same block (and know it). Take a look at the source for Proc#==, it's somewhat helpful as well. I realize this doesn't help you in the general case, though... -Justin