方法的不同行为。包括?在ruby 1.8.7和ruby 1.9之间&;2.

方法的不同行为。包括?在ruby 1.8.7和ruby 1.9之间&;2.,ruby,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

测试脚本:

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.8和更新版本之间存在差异?任何历史原因,还是1.8版本中的错误

  • 为什么符号和字符串在这里有区别?为什么这两种风格都不适用


  • 通过检查ruby 1.8和1.9(以及更高版本)之间的差异,我发现原因是:

    “实例_方法”已从字符串数组更改为符号数组

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

    x.respond_to?(:hello) # or string, both work