[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

class_eval and braces

Bertram Scharpf

1/27/2006 8:15:00 PM

Hi,

as I notice there is a difference between `class_eval' called
with a block or with a string. Why?

Bertram

--------------------
VERSION = :braces

module M
def self.included c
case VERSION
when :braces then c.class_eval {@@m = rand}
when :quotes then c.class_eval "@@m = rand"
end
end
end

class C ; @@m = "M" ; def d ; puts @@m ; end ; end
class D ; @@m = "M" ; def d ; puts @@m ; end ; end

class C ; puts @@m ; end
class D ; puts @@m ; end
C.new.d
D.new.d

class C ; include M ; end
class D ; include M ; end

class C ; puts @@m ; end
class D ; puts @@m ; end
C.new.d
D.new.d

--------------------


--
Bertram Scharpf
Stuttgart, Deutschland/Germany
http://www.bertram-...


1 Answer

ES

1/27/2006 9:34:00 PM

0

On 2006.01.28 05:15, Bertram Scharpf wrote:
> Hi,
>
> as I notice there is a difference between `class_eval' called
> with a block or with a string. Why?

Closures again. The @@m in the block is the @@m of M,
not the including class. To see this, add a line to
your code:

> VERSION = :braces
>
> module M
> def self.included c
> case VERSION
> when :braces then c.class_eval {@@m = rand}
> when :quotes then c.class_eval "@@m = rand"
> end
> end
> end
>
> class C ; @@m = "M" ; def d ; puts @@m ; end ; end
> class D ; @@m = "M" ; def d ; puts @@m ; end ; end
>
> class C ; puts @@m ; end
> class D ; puts @@m ; end
> C.new.d
> D.new.d
>
> class C ; include M ; end
> class D ; include M ; end
>
> class C ; puts @@m ; end
> class D ; puts @@m ; end
> C.new.d
> D.new.d

module M; puts @@m; end

> Bertram


E