Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a hash literal called a hash literal in Ruby?

Tags:

ruby

hash

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".

enter image description here

In Ruby, you have two data types:

  • hash
  • hash literals

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"
like image 274
Jonathan Komar Avatar asked Jun 26 '17 12:06

Jonathan Komar


Video Answer


2 Answers

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 Arrays

a = Array.new
a.push(1)
a << 2

Or, with array literal

a = [1, 2]
like image 148
Ursus Avatar answered Nov 09 '22 12:11

Ursus


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.

like image 38
ndnenkov Avatar answered Nov 09 '22 11:11

ndnenkov