我正在尝试使用Ruby,并对以下行为感到困惑。在文件test.rb
中,我有以下代码:
def my_method
puts "Output of my_method"
end
define_method(:my_other_method) do
puts "Output of my_other_method"
end
puts methods
我使用ruby test.rb
从命令行运行此文件,输出是方法列表:
to_s
inspect
my_other_method
nil?
===
=~
!~
eql?
hash
<=>
class
singleton_class
clone
dup
itself
taint
tainted?
untaint
untrust
untrusted?
trust
freeze
frozen?
methods
singleton_methods
protected_methods
private_methods
public_methods
instance_variables
instance_variable_get
instance_variable_set
instance_variable_defined?
remove_instance_variable
instance_of?
kind_of?
is_a?
tap
send
public_send
respond_to?
extend
display
method
public_method
singleton_method
define_singleton_method
object_id
to_enum
enum_for
==
equal?
!
!=
instance_eval
instance_exec
__send__
__id__
如您所见,my_other_method
位于列表中,但my_method
不是。是什么原因造成的?
答案 0 :(得分:1)
如您所见,my_other_method在列表中,但my_method不在。 是什么原因造成的?
Ruby在顶层处理defs
与类中的defs
不同:toplevel defs成为Object类的私有方法。然而:
Object#methods:返回public和protected的名称列表 方法...
def my_method
puts "Output of my_method"
end
define_method(:my_other_method) do
puts "Output of my_other_method"
end
print "public and protected:\n\t"
puts methods.grep(/my/)
print "private:\n\t"
puts private_methods.grep(/my/)
--output:--
public and protected:
my_other_method
private:
my_method
它没有记录,但define_method()
实际上创建了public
方法:
print "public:\n\t"
puts public_methods.grep(/my/)
--output:--
public:
my_other_method
和
p Object.public_methods.grep(/my/)
--output:--
[:my_other_method]
答案 1 :(得分:1)
在顶层调用def
会将方法声明为Object
类的私有方法,因此您无法在公共方法列表中看到它。但是你仍然可以直接在顶层和任何类的对象内部的任何地方调用它。
示例:
def my_method
puts "Output of my_method"
end
class Foo
def use_my_method
my_method # it can be called there
end
end
Foo.new.use_my_method
my_method