Forum: Ruby class_eval and braces

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bertram S. (Guest)
on 2006-01-27 22:17
(Received via mailing list)
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
Eero S. (Guest)
on 2006-01-27 23:35
(Received via mailing list)
On 2006.01.28 05:15, Bertram S. 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:

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

  module M; puts @@m; end

> Bertram


E
This topic is locked and can not be replied to.