方法的不同行为包括?红宝石1.8.7和红宝石1.9&之间2

时间:2015-03-09 13:32:15

标签: ruby

测试脚本:

class X
  def hello
    puts "hello"
  end
end

x = X.new
puts x.methods.include? :hello
puts x.methods.include? 'hello'

使用ruby 1.8.7:

$ ruby -v
ruby 1.8.7 (2013-06-27 patchlevel 374) [x86_64-linux]
$ ruby test.rb
false
true

使用ruby 1.9.3和ruby 2.1,2.2:

$ ruby -v
ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-linux]
$ ruby test.rb
true
false
$ ruby -v
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-linux]
$ ruby test.rb
true
false
  1. 为什么1.8和更新版本之间存在差异?任何历史原因还是1.8版本中的错误?

  2. 为什么符号和字符串在这里有所区别?为什么它不适用于这两种风格?

1 个答案:

答案 0 :(得分:0)

通过检查ruby 1.8和1.9(以及之后)之间的区别,我发现原因是:

'instance_methods'已从字符串数组更改为符号数组

检查“方法是否已定义”的正确方法是:

x.respond_to?(:hello) # or string, both work
相关问题