Forum: Ruby method def in method vs method def in block

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kyung won C. (Guest)
on 2008-11-21 10:52
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^^
#####################
Peña, Botp (Guest)
on 2008-11-21 11:36
(Received via mailing list)
From: Kyung won Cheon [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
This topic is locked and can not be replied to.