One minute
Difference between to_x and to_xxx methods โ๏ธ
Let's take an example of to_s
and to_str
here.
Both are used to transform a value from one type to another. We usually use to_s
to convert an object into string while to_str
allows you to verify that the object can be considered as string.
Code Snippet -
# String
โฏ "Ruby".to_s #=> "Ruby"
โฏ "Ruby".respond_to?(:to_str) #=> true
โฏ "Ruby".to_str #=> "Ruby"
# Integer
โฏ 10.to_s #=> "10"
โฏ 10.respond_to?(:to_str) #=> false
โฏ 10.to_str #=> NoMethodError: undefined method `to_str' for 10:Integer
Read other posts
comments powered by Disqus