Using Ruby Symbols

前端 未结 5 994
无人及你
无人及你 2020-12-02 23:56

First time I tried learning Ruby was 2 years ago, now I have started again. The reason I stopped was because I could not understand the Symbol class. And now I am at the sam

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 00:32

    Symbols are used for naming things in the language: the names of classes, the names of methods etc. These are very like strings, except they can never be garbage collected, and testing for equality is optimised to be very quick.

    The Java implementation has a very similar thing, except that it is not available for runtime use. What I mean is, when you write java code like obj.someMethod(4), the string 'someMethod' is converted by the compiler into a symbol which is embedded in a lookup table in the .class file. These symbols are like 'special' strings which are not garbage collected, and which are very fast to compare for equality. This is almost identical to Ruby, except that Ruby allows you to create new symbols at runtime, whereas Java only allows it at compile time.

    This is just like creating new methods -- Java allows it at compile time; Ruby allows it at runtime.

提交回复
热议问题