Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

In the Wild

In practice, the line between symbols and regular strings is sometimes a bit blurry. It is, for example, trivially easy to turn a symbol into a string: You just use the ubiquitous to_s method:

the_string = :all.to_s

To go in the reverse direction, you can use the to_sym method that you find on your strings:

the_symbol = 'all'.to_sym

The blurriness between symbols and strings sometimes also extends into the minds of Ruby programmers. For example, every object in Ruby has a method called public_methods, which returns an array containing the names of all of the public methods on that object. Now, you might argue that method names are the poster children for objects that stand for something (in this case a bit of code), and therefore the public_methods method should return an array of symbols. But call public_methods in a pre-1.9 version of Ruby, like this:

x = Object.new
pp x.public_methods

And you will get an array of strings, not symbols:


Is there something wrong with our reasoning? Apparently not, because in Ruby 1.9 public_methods does indeed return an array of symbols:


The lesson here is that if you find symbols a bit confusing, you seem to be in very good company.

  • + Share This
  • 🔖 Save To Your Account