# Difference between class\_eval and just adding the function?

**URL:** <https://www.ruby-forum.com/t/difference-between-class-eval-and-just-adding-the-function/128488>\
**Category:** Ruby\
**Created:** [February 8, 2008, 12:55am UTC](https://www.ruby-forum.com/t/difference-between-class-eval-and-just-adding-the-function/128488 "2008-02-08T00:55:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ericgoodwin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/c68b51/32.png) [@ericgoodwin](https://www.ruby-forum.com/u/ericgoodwin)\
**Post date:** [February 8, 2008, 12:55am UTC](https://www.ruby-forum.com/t/difference-between-class-eval-and-just-adding-the-function/128488/1 "2008-02-08T00:55:12Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![ericgoodwin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/c68b51/32.png) [@ericgoodwin](https://www.ruby-forum.com/u/ericgoodwin)\
**Post date:** [February 8, 2008, 1:24am UTC](https://www.ruby-forum.com/t/difference-between-class-eval-and-just-adding-the-function/128488/2 "2008-02-08T01:24:38Z")

</div>

On Feb 7, 2008 5:55 PM, Aryk G. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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
