public_method_defined?
- 在
A
类中定义了一个hello
方法,使用public_method_defined?
就可以判断是不是存在 :
PS C:\Users\Administrator\Rubycode> irb --simple-prompt
>> class A
>> def hello
>> puts "hello hi"
>> end
>> end
>> A.public_method_defined? "hello"
=> true
>> A.public_method_defined? "he"
=> false
- 在
B
类中使用了attr_reader
,之前笔记17. 提过,相当于提供一个read
函数 :
>> class B
>> attr_reader :he
>> def hello
>> end
>> end
=> :hello
>> B.public_method_defined? "hello"
=> true
# 因为使用attr_reader :he 相当于名为 he 的read函数,所以这里输出true
>> B.public_method_defined? "he"
=> true
method_missing
- 创建一个
C
类,并且重写method_missing
,目的是让对象识别不存在的方法,这里再做一个细致的划分,会识别出以hello_
字符开头的方法名 ,遇到这种方法输出我们定义的信息 :
PS C:\Users\Administrator\Rubycode> irb --simple-prompt
>> class C
>> def method_missing(m, *args)
>> if m.to_s.start_with?("hello_")
>> puts "not start with hello_"
>> else
?> super
>> end
>> end
>> end
=> :method_missing
>> c = C.new
=> #<C:0x00000003034488>
- 很明显并不存在一个叫做
a_method
的方法,同时这个字符串也不以hello_
开头,借由代码中的super
关键词会调用默认的(其实是由Ruby Kernel module
定义的)如下的常见错误信息提示 :
>> c.a_method
NoMethodError: undefined method `a_method' for #<C:0x00000003034488>
Did you mean? method
from (irb):6:in `method_missing'
from (irb):11
from C:/Ruby23-x64/bin/irb.cmd:19:in `<main>'
- 当遇见以
hello_
开头的不存在的方法时,会输出自己定义的信息 :
>> c.hello_world
not start with hello_
=> nil
>> c.hello_day
not start with hello_
=> nil
reference
《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
4.3. The method_missing methodpublic_method_defined?
http://apidock.com/ruby/Module/public_method_defined%3F
すぅすぅ・・・zzZ
/\___
/__ヾ )
/(-ω-=)~ /
/ ̄U⌒ U⌒ ̄)
/ ∴∵∴∵ /
`/ ∴∵∴∵ /
(______ノ
http://emoji.vis.ne.jp/neruyo_3koma3.htm