class_eval and braces

B

Bertram Scharpf

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
 
E

Eero Saynatkari

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


E
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top