[Ruby笔记]21.Ruby public_method_defined? 以及 method_missing

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 method

public_method_defined?
http://apidock.com/ruby/Module/public_method_defined%3F

すぅすぅ・・・zzZ
     /\___
     /__ヾ  )
   /(-ω-=)~ /
   / ̄U⌒ U⌒ ̄)
  / ∴∵∴∵ /
`/ ∴∵∴∵ /
(______ノ

http://emoji.vis.ne.jp/neruyo_3koma3.htm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值