I understand Hash : hash1 = Hash["a" => 100 , "b" => 200]
But i cant figure out what hash2 = Hash[:a => 100 , :b => 200]
is.
Whats the difference between the keys? What is the use of a key with :
?
:a
is a symbol, whereas "a"
is a string.
:a == "a"
# => false
:a.to_s
# => "a"
Therefore, given the following hashes,
h1 = Hash["a" => 100, "b" => 200]
h2 = Hash[:a => 100, :b => 200]
We can access their values as follows
h1[:a]
# => nil
h1["a"]
# => 100
h2[:a]
# => 100
h2["a"]
# => nil
ActiveSupport has a HashWithIndifferentAccess that allows interchangeable :a
and "a"
.
Both symbols and strings can be used as hash keys. The keys which start with :
are symbols.
Symbols are immutable (they can't be changed) and exist only once in memory:
:foo.object_id == :foo.object_id #=> true
'foo'.object_id == 'foo'.object_id #=> false
Every time you use a string in Ruby it creates a new object, but this is not true for symbols. For this reason they are used frequently in Ruby as hash keys. Happily they are also one character shorter to type than strings.
Symbols are so common as hash keys in ruby that ruby 1.9 introduced a condensed syntax especially for using symbols as keys.
hash2 = Hash[:a => 100 , :b => 200]
Can also be written:
hash2 = Hash[a: 100, b: 200]
Or more commonly:
hash2 = {a: 100, b: 200}
..if you are using symbols.
More info about symbols vs strings.
Adding to @Yu Hao's answer. hash1[:a] is not same as hash1["a"] :string is symbol and "string" is regular ruby string. Symbol is immutable and may perform better in certain cases in comparison to String(which is mutable in Ruby). You can read more about difference between symbol and string.