The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Ruby constants have weird behavior in class_eval

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Paul Gross

Posts: 152
Nickname: pgross
Registered: Sep, 2007

Paul Gross is a software developer for ThoughtWorks.
Ruby constants have weird behavior in class_eval Posted: Sep 27, 2007 8:04 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Paul Gross.
Original Post: Ruby constants have weird behavior in class_eval
Feed Title: Paul Gross's Blog - Home
Feed URL: http://feeds.feedburner.com/pgrs
Feed Description: Posts mainly about ruby on rails.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Paul Gross
Latest Posts From Paul Gross's Blog - Home

Advertisement

I was playing with some code the other day, and I noticed that constants work strangely in class_eval blocks. Sometimes it can find the constant, and sometimes it cannot.

For example, say we have a class with a constant:

class Foo
  CONS = 'const'
end
Now, if we reopen the class and print the constant, it works as expected:

>> class Foo
>>   puts CONS
>> end
const
However, if we use a class_eval instead of reopening the class, ruby cannot find the constant:

>> Foo.class_eval { puts CONS }
NameError: uninitialized constant CONS
        from (irb):12
        from (irb):11:in `class_eval'
        from (irb):11
It gets even stranger. We can still see the constant in the list of constants:

>> Foo.class_eval { puts self.constants }
CONS
Furthermore, a const_get still works:

>> Foo.class_eval { puts const_get(:CONS) }
const
Finally, if we try the class_eval again with a string instead of a block, it works:

>> Foo.class_eval "puts CONS" 
const

Apparently, constants have a problem with blocks inside of class_eval.

Read: Ruby constants have weird behavior in class_eval

Topic: Method Dispatch Previous Topic   Next Topic Topic: Tweets on 2007-09-25

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use