Ruby For Rails class_eval question

When I run the following example on page 349, I get the error message:

NoMethodError: undefined method `some_method’ for #<C:0x2e3d698 @x=1>
from (irb):94
from ?:0

c = Class.new
c.class_eval do
def some_method
puts “Created in class_eval”
end
end
c = C.new
c.some_method

How to run this example? I followed the suggestion on the Manning’s
errata page with no luck. TIA.
A.

It works now. Why does it have to be constant?

Bala P. <[email protected]…> writes:

c = Class.new
Your non-capitalization above is incorrect. The new class should be a
constant.
Try C = Class.new
c.class_eval do

def some_method
puts “Created in class_eval”
end
end
c = C.new
Well, you haven’t defined C because of the capitalization issue above.
c.some_method

Bala P. wrote:

It works now. Why does it have to be constant?

It doesn’t really have to be. It’s just a convention that classes are
defined into constants.

You can just as easily do:

x = Class.new
x.class_eval do
def some_method
puts “Created in class_eval”
end
end
c = x.new
c.some_method

The reason your first example failed was b/c you were inconsistently
mixing ‘c’ and ‘C’.

Hi –

On Tue, 10 Oct 2006, Bala P. wrote:

puts “Created in class_eval”
end
end
c = C.new
c.some_method

How to run this example? I followed the suggestion on the Manning’s errata page with no luck. TIA.

The erratum has an erratum… The two lines I provided are run
together into one. They should be split, as below.

The whole thing should be:

c = Class.new
c.class_eval do
def some_method
puts “Created in class_eval”
end
end

c_instance = c.new
c_instance.some_method

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

Hi –

On Wed, 11 Oct 2006, Kian Wright wrote:

x.class_eval do
def some_method
puts “Created in class_eval”
end
end
c = x.new
c.some_method

The reason your first example failed was b/c you were inconsistently
mixing ‘c’ and ‘C’.

My fault – it was wrong in the first printing, and the erratum has
two lines run together as one. (See my other reply on this thread for
the working version.)

David


David A. Black | [email protected]
Author of “Ruby for Rails” [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB’s Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs