Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two Ruby symbols?

I discovered this after playing around with object ids.

ObjectSpace._id2ref(2648)
=> :**
ObjectSpace._id2ref(6688)
=> :**
ObjectSpace._id2ref(2648) == ObjectSpace._id2ref(6688)
=> false

The first one is the symbol for the exponentiation operator;

2.send(ObjectSpace._id2ref(2648), 3)
=> 8
2.send(ObjectSpace._id2ref(6688), 3)
NoMethodError: undefined method `**' for 2:Fixnum

But the second one somehow isn't? I assume they just look the same after being passed to #print. But what is the difference? Is one of them somehow a unicode symbol?

UPDATE: The second one is probably the new double splat for keyword arguments, but I can't seem to verify this.

like image 643
Alex Altair Avatar asked Mar 01 '14 21:03

Alex Altair


People also ask

What are Ruby symbols?

Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.

What is the difference between a symbol and a string Ruby?

What is the difference between a symbol and a string? A string, in Ruby, is a mutable series of characters or bytes. Symbols, on the other hand, are immutable values. Just like the integer 2 is a value.

What is a valid difference between strings and symbols in Ruby on Rails?

While symbols and strings give you the same results when used as keys in hashes, they are not the same thing. A symbol is immutable while a string is mutable. You can't change a symbol once it's created. :locked on different lines in your code is the same object.

What does @variable mean in Ruby?

In Ruby, the at-sign ( @ ) before a variable name (e.g. @variable_name ) is used to create a class instance variable.


1 Answers

These commands may be illuminating:

ObjectSpace._id2ref(2648).class.ancestors
ObjectSpace._id2ref(6688).class.ancestors
like image 56
John Bachir Avatar answered Sep 20 '22 06:09

John Bachir