[Ruby] How to get the value by specifying the key. Differences between hashes, symbols and fetch

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')

table of contents

  1. Differences between hashes, symbols and fetches (#ハッシュシンボルfetchの違い)
  2. (1) Difference depending on the format of the original object
  3. ② Do you want to display an error with a key that does not exist?
  4. fetch method
  5. Exception Handling 1
  6. Exception Handling 2
  7. When both exception handling 1 and exception handling 2 are described

## Differences between hashes, symbols and fetch The difference between them is

-① ** What is the original object format **? -② Do you want to display ** error ** with a key that does not exist?

There are two points.


## ① Difference depending on the format of the original object

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.


## ② Do you want to ** display an error ** with a key that does not exist? As you can see in the above example, if you specify a symbol and hash, ** no error will occur even if the specified key does not exist, and `nil` will be returned. ** **

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


## fetch method In the fetch method, you can specify the display contents at the time of error by describing the second argument or block. (Exception handling can be easily specified)

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.


### Exception handling 1

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

** ▼ Specify with a variable 1 **

Specified by a character string


obj = {:a=>1, :b=>2, :c=>3}

e = "error"
obj.fetch(:g, e)

=> "error"

** ▼ Specify with a variable 2 ** It is also possible to assign a value to a variable in parentheses.

Specified by a character string


obj = {:a=>1, :b=>2, :c=>3}
obj.fetch(:g, e = "error")

=> "error"

### Exception handling 2 ・`object.fetch(Key){|variable|Exception handling}`

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"

** ▼ Variable expansion ** The value of a variable can be displayed as a character string by describing `# {variable}` in the character string `" "`.
** ▼ When no variable is specified ** If no variable is specified, only the exception handling description is returned.

python


obj = {:a=>1, :b=>2, :c=>3}
obj.fetch(:g){ "It is an error" }

=> "It is an error"

### When both exception handling 1 and exception handling 2 are described If both exception handling 1 and exception handling 2 are described, exception handling 2 is returned together with a warning message.

python


obj.fetch(:g, "error1"){ "ERROR2" }
warning: block supersedes default value argument
=> "ERROR2"

supersedes means to replace.

Recommended Posts

[Ruby] How to get the value by specifying the key. Differences between hashes, symbols and fetch
[Java] How to get the key and value stored in Map by iterative processing
[ruby] How to assign a value to a hash by referring to the value and key of another hash
[Ruby] How to get the tens place and the ones place
[Ruby] How to use the map method. How to process the value of an object and get it by hash or symbol.
Differences between Ruby strings and symbols [Beginner]
[Ruby] I want to extract only the value of the hash and only the key
How to create your own annotation in Java and get the value
[Ruby] How to use is_a? Differences from kind_of? and instance_of ?. How to check the type and return a boolean value.
[Understanding] Differences between hashes and arrays in Ruby
Ruby How to convert between uppercase and lowercase
I want to get the value in Ruby
Differences between Java, C # and JavaScript (how to determine the degree of obesity)
[Java] How to get the maximum value of HashMap
Let's sort out the differences between Java substring and C # Substring, and how to port them.
Difference between Java and JavaScript (how to find the average)
How to retrieve the hash value in an array in Ruby
[Rails] Differences between redirect_to and render methods and how to output render methods
About Ruby hashes and symbols
Differences in how to handle strings between Java and Perl
How to use the certificate and private key created by Docker's BASIC authentication with AWS ALB
How to pick up the input value by asynchronous communication and output the desired data from the server
[Rails] How to get the URL of the transition source and redirect
[Swift5] How to get an array and the complement of arrays
Get the current date and time by specifying the time zone in Thymeleaf
How to get the id of PRIMAY KEY auto_incremented in MyBatis
How to get and add data from Firebase Firestore in Ruby
[For beginners] How to get the Ruby delayed railway line name
[Java] How to convert from String to Path type and get the path
Easy to understand the difference between Ruby instance method and class method.
[Ruby] Difference between get and post
[Java] How to get the current date and time and specify the display format
Get a rough idea of the differences between protocols, classes and structs!
How to get the value after "_" in Windows batch like Java -version
Use MyBatis to get Map with key as identifier and value as Entity
How to embed and display youtube videos in Rails (You can also get the URL you entered by editing)
How to get date data in Ruby
Summary of hashes and symbols in Ruby
[Java] How to get the current directory
How to find the tens and ones
How to pass the value to another screen
How to get the date in java
[Easy] How to upgrade Ruby and bundler
[Ruby] Learn how to use odd? Even? And count the even and odd numbers in the array!
[swift5] How to transition from the app to an external site by specifying the URL
[Ruby] How to calculate the total amount using the initialize method and class variables
How to find the distance and angle between two points on a plane
[Rails] How to decide the destination by "rails routes"
How to find the cause of the Ruby error
[Ruby] How to convert from lowercase to uppercase and from uppercase to lowercase
[Java] How to get and output standard input
[Ruby] How to use gsub method and sub method
How to get today's day of the week
Summarize the differences between C # and Java writing
How to get and study java SE8 Gold
Try to get redmine API key with ruby
[Ruby] Difference between puts and return, output and return value
Ruby: Differences between class methods and instance methods, class variables and instance variables
How to find the total score and average score
[Java] How to get the redirected final URL
To get Ruby Silver at the last minute