We Recommend

Beginning Ruby: From Novice to Professional Beginning Ruby: From Novice to Professional
Beginning Ruby is a thoroughly contemporary guide for every type of reader wanting to learn Ruby, from novice programmers to web developers to Ruby newcomers. It starts by explaining the principles behind object-oriented programming and within a few chapters builds toward creating a genuine Ruby application.


Posted By

cczona on 03/13/08


Tagged

ruby String tos tostr


Versions (?)


to_str vs to_s


Published in: Ruby 


URL: http://whytheluckystiff.net/articles/rubyOneEightOh.html

  1. With to_str, Matz is giving us a simpler way of demonstrating that our classes can be used as strings directly... So why not use to_s? Because to_s coerces objects into strings. So, to_str is an implicit cast, whereas to_s is an explicit cast...
  2.  
  3. ...[T]here is a reason that to_s is shorter. First, it implies that the object isn't really much of a string, so we're only using the first letter...
  4.  
  5. With to_str, we're tagging an object as much closer to being a string, so we give it the first three letters. It's almost half of a string!

Report this snippet 

You need to login to post a comment.