Difference between class_eval and just adding the function?

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?

On Feb 7, 2008 5:55 PM, Aryk G. [email protected] wrote:

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

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