Ruby Tuesday – Symbol#id2name

Today’s Ruby Tuesday is on Symbol#id2name.

`Symbol#id2name` returns the string value for a given symbol that is the name of the symbol.

:foo.id2name
# => "foo"
:'HelloWorld'.id2name
# => "HelloWorld"
:nil.id2name
# => "nil"
:''.id2name
# => ""

If we scroll down the documentation page for `Symbol` down to Symbol#to_s, we can see it is using `id2name` in the example.

So let’s see if we can quickly notice a difference in what is returned.

:foo.to_s
# => "foo"
:''.to_s
# => ""
:nil.to_s
# => "nil"

We can see the behavior appears to indeed be the same, so we will dig a little deeper.

If you go to the documentation page for both methods, and then toggle the source for both of the methods, you can see they both use the underlying procedure `rb_sym_to_s`, and are infact aliases for each other.

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *