ruby try\u convert类方法未转换

ruby try\u convert类方法未转换,ruby,Ruby,在字符串类(2.2.0版)的ruby文档中,我找到了类方法“try_convert”,它可以执行以下操作: Try to convert obj into a String, using #to_str method. Returns converted string or nil if obj cannot be converted for any reason. 因此,我决定对其进行测试,并使用以下代码和结果进行了测试 require 'bigdecimal' z=BigDecimal.

在字符串类(2.2.0版)的ruby文档中,我找到了类方法“try_convert”,它可以执行以下操作:

Try to convert obj into a String, using #to_str method. Returns converted string or nil if obj cannot be converted for any reason.
因此,我决定对其进行测试,并使用以下代码和结果进行了测试

require 'bigdecimal'

z=BigDecimal.new "12.4"
puts z
zc=String.try_convert(z)

i=365
ic=String.try_convert(i)

puts "Test of try_convert on a bigdecimal. The result is: #{zc.nil? ? 'nil' : zc }"
puts "While, the #to_s method on z returns: #{z.to_s}"

puts "The integer i, converted with try_convert is: #{ic.nil? ? 'nil' : ic}"
puts "While, the #to_s method on i returns: #{i.to_s}"

class MyClass 
end

c=MyClass.new
cc=String.try_convert(c)
puts "Test of try_convert on a custom class. The result is: \"#{cc.nil? ? 'nil' : cc}\""
puts "While, the #to_s method on c returns \"#{c.to_s}\""
结果:

在bigdecimal上测试try\u转换。结果是:nil
而z上的#to_s方法返回:0.124E2

使用try\u convert转换的整数i为:nil
而i上的#to_s方法返回:365

在自定义类上测试try_convert。结果是:“nil
而c上的#to_s方法返回#


所以我很困惑:在一开始,我似乎很清楚try\u convert会尝试调用参数上的to\u方法,但这个例子似乎表明这不是真的。我错过了什么?这个方法的作用是什么?

try\u convert
实际上试图调用参数上的
to\u str
,而不是
to\u s

class Foo
  def to_str
    "hello!"
  end
end

String.try_convert(Foo.new) # => "hello!"

to_str
通常用于表示可以使用对象来代替字符串(与仅使用字符串表示不同)。

我将引用您自己问题中的两行,并加上强调:

在我看来很清楚,
try\u convert
会尝试调用参数上的
to\s
方法

尝试使用
#to_str
方法将
obj
转换为
字符串


发现差异了吗?

我当然发现了。我希望我的错误对其他人有用。我通常不太注意每个单独的名称,不管是方法名称还是其他名称,而是总体上的“命名约定”。例如,rails中的单数和复数名称现在对我来说非常清楚,我不会混淆它们,因为我希望它们以不同的、明确的含义存在。在这里,我甚至不知道是否存在第二个,从一个对象获取字符串的方式略有不同,所以我看到它时,我没有注意到它实际上是一个完全不同的名称。