[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

about searching constant

Kyung won Cheon

12/31/2008 2:21:00 PM

class A
WHY = "I don't know why!!"

def self.foo
instance_eval("WHY")
end
end

puts A.instance_eval { foo } # => I don't know why!!
puts A.instance_eval("WHY") # => uninitialized constant Class::WHY
(NameError)

###############
# Help Me^^
###############
--
Posted via http://www.ruby-....

5 Answers

bermonruf

1/1/2009 7:09:00 AM

0

[Note: parts of this message were removed to make it a legal post.]

Weird, if you use A.instance_eval("self::WHY") it simply works... can anyone
explain it?


On Wed, Dec 31, 2008 at 12:20 PM, Kyung won Cheon <kdream95@gmerce.co.kr>wrote:

> class A
> WHY = "I don't know why!!"
>
> def self.foo
> instance_eval("WHY")
> end
> end
>
> puts A.instance_eval { foo } # => I don't know why!!
> puts A.instance_eval("WHY") # => uninitialized constant Class::WHY
> (NameError)
>
> ###############
> # Help Me^^
> ###############
> --
> Posted via http://www.ruby-....
>
>


--
Bernardo Rufino

Brian Candler

1/1/2009 8:57:00 AM

0

It also works if you change instance_eval to class_eval (or
module_eval).

However I'm not entirely sure of the difference between the former and
the latter two.
--
Posted via http://www.ruby-....

Mike Gold

1/2/2009 9:27:00 AM

0

Kyung won Cheon wrote:
> class A
> WHY = "I don't know why!!"

Umm ... You already posted this question, and I answered it.
Did you not like the answer?

http://www.ruby-...to...

Also as Brian mentioned, module_eval/class_eval works.

An invisible parameter is passed to a block (search for cases of
specific_eval in eval.c) which is used for constant lookups.

For A.module_eval { } and A.class_eval { }, that invisible parameter
is A. But for A.instance_eval { }, it is A's singleton class.

The constant lies in A, not in A's singleton class.
--
Posted via http://www.ruby-....

Brian Candler

1/2/2009 2:56:00 PM

0

Bernardo Rufino wrote:
> Weird, if you use A.instance_eval("self::WHY") it simply works... can
> anyone
> explain it?

Because that's the same as A::WHY

(i.e. inside foo.instance_eval { ... }, self is foo)

--
Posted via http://www.ruby-....

Kyung won Cheon

1/5/2009 1:35:00 AM

0

Mike Gold wrote:

> An invisible parameter is passed to a block (search for cases of
> specific_eval in eval.c) which is used for constant lookups.
>
> For A.module_eval { } and A.class_eval { }, that invisible parameter
> is A. But for A.instance_eval { }, it is A's singleton class.
>
> The constant lies in A, not in A's singleton class.

> You must be inside "class
> A" (or "module A") to get the constant lookup of WHY == A::WHY.

I understand it now...

Thank you!!

--
Posted via http://www.ruby-....