Make delicious recipes!

Colon variable in Ruby



Colon variable refers to :abc type variables you might have seen in Ruby.
They are called Ruby symbols.
In comparison to other languages, a Ruby symbol is not a variable because it cannot be assigned a value.
Also, a Ruby symbol is not a reference to another variable nor is it a pointer to a memory location.
Still a symbol has a value and whenever the name of the symbol is same, its value is the same.
An example will make it more clear.

# It is trivial to assign a value to a variable.
abc = "1"
=> "1"

# But a symbol cannot be assigned any value.
:a = "1"
# SyntaxError: A symbol cannot be assigned a value

# Can use a variable as a map-key (You know already)
m = {abc => "1"}
=> {"1"=>"1"}

# Can use a string as a map-key (You know already)
m = {"def" => "1"}
=> {"def"=>"1"}

# Can also use a symbol as a map-key (Most common use case)
m = {:a => "1"}
=> {:a=>"1"}

# Can use same symbol as key in another map
m2 = {:a => "2"}
=> {:a=>"2"}

# And it won't affect the previous map.
m
=> {:a=>"1"}

m2
=> {:a=>"2"}
Now it would be easier to understand what a ruby symbol really is.
A ruby symbol is like an Enum constant in Java or C++ like:
public enum Color {RED, BLUE, GREEN};
Think of a Ruby symbol as being equivalent to RED, BLUE or GREEN.
It is illegal to assign a value to these enum constants as RED = 5 but they can be used as keys in a hash-map.
Same holds true for ruby symbols.
As seen above, assigning a value to a symbol gives an error but it is perfectly OK to use them in maps.

Also note that just like enum constants, two ruby symbols with the same name have the same identity.
So they match by equal? operator (compares identity) as well as by eql? operator (compares logical equality)
:b.equal?:b
=> true
:b.eql?:b
=> true

This is so because two similarly-named symbols in Ruby are actual the same object.
You can verify that by checking their object_id
:a.object_id
=> 351218
:b.object_id
=> 71218
:a.object_id
=> 351218
:b.object_id
=> 71218







Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal