This is probably something you learn in programming 101.
Disclaimer: I have no formal programming training. I am self-taught.
For me, literal hash is like what this website suggests: a third editable hash called "corned beef hash".
In Ruby, you have two data types:
Why is one called a literal? Is it because you literally type out the associative array? The website above claims it is because the definition is inline. If so, why is the hash not also called literal when you can type it out like this:
states = Hash.new
states["CA"] = "California"
states["MA"] = "Massachusetts"
states["NY"] = "New York"
states["MA"].reverse #=> "sttesuhcassaM"
The data type is just one: Hash
. Hash
is a class. You can instantiate objects and use them
h = Hash.new
h.store("CA", "California")
h["MA"] = "Massachusetts"
A literal is just a shortcut which let you create objects of that class without explicitly use that class.
h = { "CA" => "California", "MA" => "Massachusetts" }
Same for Array
s
a = Array.new
a.push(1)
a << 2
Or, with array
literal
a = [1, 2]
Your confusion stems from this misconception:
In Ruby, you have two data types:
- hash
- hash literals
Firstly, there are many more data structures in the Ruby core.
But secondly, there is no such thing as "literal hash". Hash literals refer to syntax sugar for defining hashes in place, aka literally.
# This is a hash literal
x = {foo: 42, bar: :baz}
# This is not a hash literal
x = Hash.new
x[:foo] = 42
x[:bar] = :baz
They are completely identical. The only difference is one is more convenient, while the other is more dynamic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With