# Method def in method vs method def in block

**URL:** <https://www.ruby-forum.com/t/method-def-in-method-vs-method-def-in-block/153809>\
**Category:** Ruby\
**Created:** [November 21, 2008, 9:52am UTC](https://www.ruby-forum.com/t/method-def-in-method-vs-method-def-in-block/153809 "2008-11-21T09:52:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kyung\_won\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/47e85d/32.png) [@Kyung\_won\_C](https://www.ruby-forum.com/u/Kyung_won_C)\
**Post date:** [November 21, 2008, 9:52am UTC](https://www.ruby-forum.com/t/method-def-in-method-vs-method-def-in-block/153809/1 "2008-11-21T09:52:37Z")

</div>

class A  
def aaa  
puts “called aaa by #{self}”  
def bbb  
puts “called bbb by #{self}”  
end  
end  
end

a = A.new  
p a.respond\_to?(:bbb) # =\> false  
a.aaa  
p a.respond\_to?(:bbb) # =\> true  
a.bbb

p A.public\_instance\_methods.grep(/bbb/) # =\> [“bbb”]

a2 = A.new  
a2.bbb

p a.respond\_to?(:ccc) # =\> false

a.instance\_eval do  
def ccc  
puts “called ccc by #{self}”  
end  
end

p a.respond\_to?(:ccc) # =\> true  
a.ccc

p A.public\_instance\_methods.grep(/ccc/) # =\> []

a2.ccc rescue puts $! # undefined method

#####################

# What’s the diff ??

# Help Me^^

#####################

---

<div class="post-metadata">

**Author:** ![Kyung\_won\_C](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/47e85d/32.png) [@Kyung\_won\_C](https://www.ruby-forum.com/u/Kyung_won_C)\
**Post date:** [November 21, 2008, 10:36am UTC](https://www.ruby-forum.com/t/method-def-in-method-vs-method-def-in-block/153809/2 "2008-11-21T10:36:04Z")

</div>

From: Kyung won Cheon [[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)]

# class A

# def aaa

# puts “called aaa by #{self}”

# def bbb

# puts “called bbb by #{self}”

# end

# end

# end

# 

# a = A.new

# p a.respond\_to?(:bbb) # =\> false

# a.aaa

# p a.respond\_to?(:bbb) # =\> true

# a.bbb

this is faq.

you defined bbb inside aaa, ergo, it will be “defined” until aaa is  
called, ie you have to call aaa first (just one call will do).

# p A.public\_instance\_methods.grep(/bbb/) # =\> [“bbb”]

# 

# a2 = A.new

# a2.bbb

# 

# p a.respond\_to?(:ccc) # =\> false

# 

# a.instance\_eval do

# def ccc

# puts “called ccc by #{self}”

# end

# end

you defined a method “ccc” _only_ for the object instance “a”, not all  
the instances of A.

try module\_eval or class\_eval.

A.module\_eval do  
def ccc  
puts “called ccc by #{self}”  
end  
end

# p a.respond\_to?(:ccc) # =\> true

# a.ccc

# 

# p A.public\_instance\_methods.grep(/ccc/) # =\> []

# 

# a2.ccc rescue puts $! # undefined method
