This is a personal memo.
In addition to specifying the key by hash or symbol, there is also a method of using the fetch method to fetch the value by specifying the key of the object.
・ Symbol: obj[:a]
・ Hash: obj['a'] ( obj["a"]Is the same)
・ Fetch: obj.fetch(:a)Or obj.fetch('a')
-① ** What is the original object format **? -② Do you want to display ** error ** with a key that does not exist?
There are two points.
There are ** hash ** and ** symbol ** as the method of specifying the key of the object.
** The hash is a string. The symbol is described with a colon ** in front of it. The specification when retrieving the value must match each format.
Hash format example
obj = {"a"=>1, "b"=>2, "c"=>3}
##Get value
obj2['b']
=> 2
##NG
obj[:b]
=> nil
Symbol format example
obj = {:a=>1, :b=>2, :c=>3}
##Get value
obj[:b]
=> 2
##NG
obj['b']
=> nil
That is, 'b'
and : b
are not equal.
The hash is unique to each defined object, but the difference is that all symbols are the same if they have the same key.
** Use fetch ** if you want to display an error.
python
obj = {:a=>1, :b=>2, :c=>3}
##If the value exists
obj.fetch(:b)
=> 2
##If the value does not exist case1
obj.fetch(:g)
KeyError (key not found: :g)
##If the value does not exist case2
obj.fetch("b")
KeyError (key not found: "b")
If you specify a value that does not exist, KeyError (key not found: specified key)
is returned.
・object.fetch(Key,Exception handling 1){|Variable 2|Exception handling 2 }
--Exception handling 1 can be specified by either a variable or a value --If both exception handling 1 and exception handling 2 are listed, exception handling 2 takes precedence. --The key name is entered in variable 2 of exception handling 2.
{}
In|variable|
If there is no description of, only the processing result is returned.-Object.fetch (key, exception handling)
** ▼ Specify by character string **
Specified by a character string
obj = {:a=>1, :b=>2, :c=>3}
obj.fetch(:g, "error")
=> "error"
Specified by a character string
obj = {:a=>1, :b=>2, :c=>3}
e = "error"
obj.fetch(:g, e)
=> "error"
Specified by a character string
obj = {:a=>1, :b=>2, :c=>3}
obj.fetch(:g, e = "error")
=> "error"
It is also possible to specify exception handling in the block {}
.
python
obj = {:a=>1, :b=>2, :c=>3}
obj.fetch(:g){|x| "#{x}Does not exist" }
=> "g does not exist"
python
obj = {:a=>1, :b=>2, :c=>3}
obj.fetch(:g){ "It is an error" }
=> "It is an error"
python
obj.fetch(:g, "error1"){ "ERROR2" }
warning: block supersedes default value argument
=> "ERROR2"
supersedes means to replace.