Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby try_convert class method not converting

Tags:

ruby

In the ruby doc of the String class (version 2.2.0) I've found the class method 'try_convert' that, qouting the doc itself should do:

Try to convert obj into a String, using #to_str method. Returns converted string or nil if obj cannot be converted for any reason.

So i've decided to test it, and i've done it with the following code and results.

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}\""

Results:

Test of try_convert on a bigdecimal. The result is: nil
While, the #to_s method on z returns: 0.124E2

The integer i, converted with try_convert is: nil
While, the #to_s method on i returns: 365

Test of try_convert on a custom class. The result is: "nil"
While, the #to_s method on c returns #<MyClass:0x98d12d4>

So i'm quite perplexed: in the beginning, it seemed to me quite clear that try_convert would have tried to call the to_s method on the argument, but this examples seems to show that this isn't true. What am I missing? And what is this method meant for?

like image 890
AgostinoX Avatar asked Dec 11 '25 18:12

AgostinoX


1 Answers

try_convert actually attempts to call to_str on the argument, not to_s:

class Foo
  def to_str
    "hello!"
  end
end

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

to_str is usually used to indicate that your object can be used in place of a String (not the same as just having a String representation).

like image 122
August Avatar answered Dec 13 '25 12:12

August



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!