Forum: Ruby class_eval(aString) vs class_eval(aBlock)

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.
392450979e40b958c4bdad04579e74d5?d=identicon&s=25 Gioele Barabucci (Guest)
on 2006-01-24 13:19
(Received via mailing list)
Hi,

why does class_eval behave differently is you pass a string or a block
to it?
This simple test

| class A
|   def test_str; p self.class.class_eval("@@v"); end
|   def test_blk; p self.class.class_eval { @@v }; end
| end
|
| class B < A
|   def initialize; @@v = "v.B"; end
| end
|
| B.new.test_str
| B.new.test_blk

gives this (unexpected?) result

| $ ruby ./cv2.rb
| "v.B"
| ./cv2.rb:3:in `test_blk': uninitialized class variable @@v in A (NameError)
|         from ./cv2.rb:3:in `class_eval'
|         from ./cv2.rb:3:in `class_eval'
|         from ./cv2.rb:3:in `test_blk'
|         from ./cv2.rb:11
5c7bdd14d6885c8275eaf78be41d120a?d=identicon&s=25 Eero Saynatkari (Guest)
on 2006-01-26 23:24
(Received via mailing list)
On 2006.01.24 21:19, Gioele Barabucci wrote:
> | class B < A
> | ./cv2.rb:3:in `test_blk': uninitialized class variable @@v in A (NameError)
> |         from ./cv2.rb:3:in `class_eval'
> |         from ./cv2.rb:3:in `class_eval'
> |         from ./cv2.rb:3:in `test_blk'
> |         from ./cv2.rb:11

Reason for that is that all blocks are closures (they 'enclose' the
scope they were defined in). In this case, @@v is bound to the @@v
in class A at the time you create the block.

> Gioele <dev@gioelebarabucci.com>


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