Hacker News new | ask | show | jobs
by berkes 1534 days ago
In Ruby `"Foo" == "Foo"` returns true. Whereas `"Foo".object_id == "Foo".object_id` returns false: They are not the same object, but report being equal.

OTOH, symbols return true for both: they are the exact same object.

It's not just about speed though: symbols are somewhat limited in what they can be made of. They follow the same limitations as methods and variables. So often symbols are used when dynamically calling methods or assigning variables.

"Foo".public_send(:strip!) ¹. Which is slightly different from "Foo".public_send('strip!'). Not in outcome, but in calling. Because this is invalid syntax: "Foo".public_send(:one-two three) whereas this isn't: "Foo".public_send('one-two three'). Technically, I guess Ruby can have a method that is named "one-two three" but that would be really nasty to call. Symbols protect a lot against this.

And therefore are used in this context a lot.

¹ The exclamation mark can be a part of a method and symbol in ruby. As can the question-mark and some other sugar-ish stuff like [].

2 comments

> symbols are somewhat limited in what they can be made of

Only in the unquoted literal syntax. The :symbol form follows Ruby's usual identifier rules but there's also a :"quoted symbol" syntax. You can also send :to_sym or :intern to any string and it will be converted to a symbol.

https://ruby-doc.org/core/String.html#method-i-to_sym

> This can also be used to create symbols that cannot be represented using the :xxx notation.

  'cat and dog'.to_sym   #=> :"cat and dog"
Ruby inherited that ?! convention fromm scheme. All mutating procedures end with ! and all predicates with !.

Prefix notation has none of those pesky limitations if you can live with it :)

Edit: oh. Scheme is painfully monomorphic. Equality for.strings is string=?. Equality for chars is char=?.

Then there is object equality (eq? ...), eqv? ("Normally eq?") and equal? which is a generic equality predicate that works for all objects (including circular data structures).

Eq? is the one you would use for symbols. Symbols are always (almost, at least) eq?. One string is only eq? To itself, but not a string containing the same content.

I think you meant to say this in your first sentence: "all predicates with ?"
Yup. Thanks. I hate writing on my phone. I make so many mistakes that I frequently wonder if I am literate when I read things I have written.