This is a personal memo.
Depending on how to get the value of the object, the structure of the target data is different between obj [: a]
and obj ['a']
.
Depends on whether the object is created with a ** symbol ** or a ** string **.
Objects that use strings are called ** hashes **.
If obj = {a: 1, b: 2}
, the property name is a symbol.
The symbol is also used to specify when acquiring data.
object
obj = {a:1, b:2}
=> {:a=>1, :b=>2}
Data acquisition
##OK
obj[:a]
=> 1
##NG
obj['a']
=> nil
Specifying the property name of a symbolic object with '''
will result in an error.
Data acquisition of an object created with a character string such as obj2 = {"a" => 1, "b" => 2}
is specified with a character string.
python
##Object definition
obj2 = {"a" => 1, "b" => 2}
=> {"a"=>1, "b"=>2}
##Data acquisition
obj2['a']
=> 1
obj2["a"]
=> 1
##NG
obj2[:a]
=> nil
Using a symbol will result in an error.