Jonathan Komar
Jonathan Komar

Reputation: 3096

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

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:

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"

Upvotes: 7

Views: 9133

Answers (3)

Ursus
Ursus

Reputation: 30056

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]

Upvotes: 21

David Aldridge
David Aldridge

Reputation: 52356

A literal is a fixed value.

It cannot be edited, unless you assign it to a variable and then modify that (although then of course you are not actually modifying the literal).

https://en.wikipedia.org/wiki/Literal_(computer_programming)

So you can assign a literal to a variable, compare a variable to a literal, compare two literals, but you cannot in general modify a literal directly.

Edit: Note that cases where a literal is modified turn out to be creating a new object, unlike the same operation performed on a variable.

2.2.5 :001 > "foo".upcase!
 => "FOO" 
2.2.5 :002 > "foo".object_id
 => 2204993280 
2.2.5 :003 > "foo".upcase!.object_id
 => 2204964760 
2.2.5 :004 > x = "foo"
 => "foo" 
2.2.5 :005 > x.object_id
 => 2204927520 
2.2.5 :006 > x.upcase!.object_id
 => 2204927520 
2.2.5 :007 > 

Upvotes: 2

ndnenkov
ndnenkov

Reputation: 36101

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.

Upvotes: 5

Related Questions