One minute
What are symbols in Ruby and what they can be used for ๐ก
The object_id
method returns the identity of an Object. If two objects have the same object_id
, they are the same (point to the same Object in memory).
Symbol with the same characters references the same Object in memory, and in case of String theyโre referencing two different objects in memory. Whenever you use a new String, Ruby allocates memory for it.
If youโre in doubt whether to use a Symbol or a String, consider whatโs more important: the identity of an object (i.e. a Hash key), or the contents (in the example above, โhello_worldโ).
Code snippet ๐
# Using Symbol
โฏ :hello_world.object_id == :hello_world.object_id
true
# Using String
โฏ "hello_world".object_id == "hello_world".object_id
false
Read other posts
comments powered by Disqus