Difference between class_eval and just adding the function?

A

Aryk Grosz

Lets say I have

module A
class B
def t
puts "hi"
end
end
end

And I want to add a function to it. Whats the difference between:

module A
class B
def new_function
puts "foo"
end
end
end

***AND***

A::B.class_eval do
def new_function
puts "foo"
end
end

Is there any difference?
 
D

Day

And I want to add a function to it. Whats the difference between:

module A
class B
def new_function
puts "foo"
end
end
end

***AND***

A::B.class_eval do
def new_function
puts "foo"
end
end

Is there any difference?

Kind of hard to read all this nesting without some kind of spacing for
help. Or did it just get stripped for me, for some reason?

Anyway, I think, if you're writing out the method ahead of time,
there's not a real difference. However, if you wanted to create
methods on the fly based on something else (who knows what...), you'd
want, of the two, class_eval. Though, really, you'd probably want to
use add_method, or whatever the name of the function for doing that is
(can't remember right now).


Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top