方法的不同行为。包括?在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
通过检查ruby 1.8和1.9(以及更高版本)之间的差异,我发现原因是: “实例_方法”已从字符串数组更改为符号数组 检查“是否定义了方法”的正确方法是:
x.respond_to?(:hello) # or string, both work