Ruby 检查类上是否定义了方法

Ruby 检查类上是否定义了方法,ruby,Ruby,如何检查方法是否直接在某个类上定义,而不是通过继承或包含/扩展?我希望在以下内容中使用类似“foo”的内容: class A def a; end end module B def b; end end class C < A include B def c; end end C.foo?(:a) #=> false C.foo?(:b) #=> false C.foo?(:c) #=> true A类 DEFA;结束 结束 模块B def

如何检查方法是否直接在某个类上定义,而不是通过继承或包含/扩展?我希望在以下内容中使用类似“foo”的内容:

class A
   def a; end
end

module B
   def b; end
end

class C < A
   include B
   def c; end
end

C.foo?(:a) #=> false
C.foo?(:b) #=> false
C.foo?(:c) #=> true
A类
DEFA;结束
结束
模块B
def b;结束
结束
C类假
C.foo?(:b)#=>假
C.foo?(:C)#=>正确
用于您可以使用的对象

如果obj响应给定的方法,则返回true

上课时请看

返回一个数组,该数组包含接收方中公共和受保护实例方法的名称

使用以下命令:

C.instance_methods(false).include?(:a)
C.instance_methods(false).include?(:b)
C.instance_methods(false).include?(:c)
方法
instance\u methods
返回此类实例将拥有的方法数组。将
false
作为第一个参数传递只返回此类的方法,而不返回超类的方法

因此
C.instance\u methods(false)
返回由
C
定义的方法列表

然后,您只需检查该方法是否在返回的数组中(这就是
include?
调用所做的)


不完全是这个问题的答案,但是如果你正在阅读这个问题,你可能会对这个问题感兴趣,它使用
.instance\u方法(false)

比如说

class Person
end

module Drummer
  def drum
  end
end

module Snowboarder
  def jump
  end
end

module Engineer
  def code
  end
end

class Bob < Person
  include Drummer
  include Snowboarder
  include Engineer

  def name
  end
end

puts "who responds to name"
puts bob.who_responds_to?(:name)
puts "\n"

puts "who responds to code"
puts bob.who_responds_to?(:code)
puts "\n"

puts "who responds to jump"
puts bob.who_responds_to?(:jump)
puts "\n"

puts "who responds to drum"
puts bob.who_responds_to?(:drum)
puts "\n"

puts "who responds to dance"
puts bob.who_responds_to?(:dance)

它适用于所有情况C.new.foo?(:a)、C.new.foo?(:b)、C.new.foo?(:C)还注意到类是对象,所以
respond\u to?
也适用于它们。旁注:
respond\u to?
将包括
方法\u缺少的任何定义,然而,
#instance_方法
不会。这也适用于所有情况。只需更新答案;只需将instance_methods的第一个参数设置为false,就可以只返回C定义的方法。我知道这个方法,但不知道它采用了这样的参数。谢谢。有时您只想检查方法是否在当前上下文中定义,而不指定类或对象。为此,您可以使用
defined?(c)#=>true
class Person
end

module Drummer
  def drum
  end
end

module Snowboarder
  def jump
  end
end

module Engineer
  def code
  end
end

class Bob < Person
  include Drummer
  include Snowboarder
  include Engineer

  def name
  end
end

puts "who responds to name"
puts bob.who_responds_to?(:name)
puts "\n"

puts "who responds to code"
puts bob.who_responds_to?(:code)
puts "\n"

puts "who responds to jump"
puts bob.who_responds_to?(:jump)
puts "\n"

puts "who responds to drum"
puts bob.who_responds_to?(:drum)
puts "\n"

puts "who responds to dance"
puts bob.who_responds_to?(:dance)
who responds to name
Bob

who responds to code
Engineer

who responds to jump
Snowboarder

who responds to drum
Drummer

who responds to dance
[this line intentionally blank because return value is nil]