# class\_eval(aString) vs class\_eval(aBlock)

**URL:** <https://www.ruby-forum.com/t/class-eval-astring-vs-class-eval-ablock/96519>\
**Category:** Ruby\
**Created:** [January 24, 2006, 1:19pm UTC](https://www.ruby-forum.com/t/class-eval-astring-vs-class-eval-ablock/96519 "2006-01-24T13:19:46Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gioele](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/8491ac/32.png) [@gioele](https://www.ruby-forum.com/u/gioele)\
**Post date:** [January 24, 2006, 1:19pm UTC](https://www.ruby-forum.com/t/class-eval-astring-vs-class-eval-ablock/96519/1 "2006-01-24T13:19:46Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![gioele](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/8491ac/32.png) [@gioele](https://www.ruby-forum.com/u/gioele)\
**Post date:** [January 26, 2006, 11:24pm UTC](https://www.ruby-forum.com/t/class-eval-astring-vs-class-eval-ablock/96519/2 "2006-01-26T23:24:04Z")

</div>

On 2006.01.24 21:19, Gioele B. 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 [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

E
