Home > Software design >  Define a hash with keys of class string without using hash rockets?
Define a hash with keys of class string without using hash rockets?

Time:01-16

A hash (with key of class String) can be defined using hash rocket syntax like so:

h = {:name => 'Charles', "name" => 'John'}

Is there a way to define it using another notation?

I tried:

a = {name: "Charles", "name": "John"}
(irb):14: warning: key :name is duplicated and overwritten on line 14
a
# => {:name=>"John"}

Also note that without any overriding, I still can't spot a way to get the key to be class String:

b = {"name": "John"}
b
# => {:name=>"John"} # "name" (String) is stored as :name (Symbol)

AFAIK it's not possible to define a hash with any String keys using the more modern hash notation (the notation that doesn't use the hash rockets). Is there any way, or should the => has rockets be used when defining a hash with a key of class String?

CodePudding user response:

The documentation really makes this pretty clear:

The older syntax for Hash data uses the “hash rocket,” =>:

h = {:foo => 0, :bar => 1, :baz => 2} h # => {:foo=>0, :bar=>1,
> :baz=>2}

Alternatively, but only for a Hash key that's a Symbol, you can use a newer JSON-style syntax...

  •  Tags:  
  • Related