[Ruby] How to use the map method. How to process the value of an object and get it by hash or symbol.

This is a personal memo.

By using the map method, you can get an array that processes each element of the original object.

object.map{|variable|processing} ┗ Variable contains each element of the object ┗ Processing result is returned as an array ┗ Non-destructive processing (as is of the original object)

table of contents

  1. For range objects (#rangeオブジェクトの場合)
  2. For arrays
  3. One-dimensional array
  4. Two-dimensional array
  5. Multidimensional Array
  6. For objects (#オブジェクトの場合)
  7. When there are two arguments
  8. Extract keys as an array (#キーを配列として取り出す)
  9. Extract values ​​as an array (#値を配列として取り出す)
  10. Process the value of the object and retrieve it as an object (#オブジェクトの値を処理してオブジェクトとして取り出す)
  11. Convert from array to symbol (#配列からシンボルに変換)
  12. Convert from array to hash (#配列からハッシュに変換)
  13. When the object has one argument

## For range objects

python


range = 1..3
range2 = range.map{|x| x*2 }

p range2   
#output
[2, 4, 6]

## For arrays ### One-dimensional array

1D


arr = [1, 2, 3]
arr2 = arr.map{|x| x*2 }

p arr2   
#output
[2, 4, 6]

### A two-dimensional array In the case of a two-dimensional array, the elements in the array are repeated.

[1, 2] * 2 = [1, 2, 1, 2]

2D


arr = [1, [2, 3]]
arr2 = arr.map{|x| x*2 }

p arr2   
#output
[2, [2, 3, 2, 3]]

### For multidimensional arrays In the case of a multidimensional array, the element without one parenthesis is repeated.

[[1, 2]] * 2 = [[1, 2], [1, 2]]

multidimensional


arr =  [1, [2,3], [4, 5, [6, 7]],[[8, 9]]]
arr2 = arr.map{|x| x*2 }

p arr2   
#output
[2, [2, 3, 2, 3], [4, 5, [6, 7], 4, 5, [6, 7]], [[8, 9], [8, 9]]]

## For objects In the case of an object, the element to be extracted depends on the number of ** arguments specified in the block **.

In addition, the processing result is ** returned as an array **.

Number of variables Contents Example of acquisition element
1 Key and value [:a, 1]
2 1st argument: key, 2nd argument: value, :a, 1

As a general usage, it is used when you want to retrieve only the key or value of an object as an array. (Specify two variables)


### When there are two arguments If there are two arguments, the key is in the first argument and the value is in the second argument.

Extract keys as an array

Extract only keys as an array


obj = {:a=>1, :b=>2, :c=>3}
obj2 = obj.map{|x, y| x }

p obj2
#output
[:a, :b, :c]

** ▼ Error case ** Processing such as four arithmetic operations cannot be performed on keys. When executed, an error occurs.

error


obj = {:a=>1, :b=>2, :c=>3}
obj2 = obj.map{|x, y| x*2 }

NoMethodError (undefined method `*' for :a:Symbol)

### Extract values ​​as an array

Take out as it is


obj = {:a=>1, :b=>2, :c=>3}
obj2 = obj.map{|x, y| y }

p obj2
#output
[1, 2, 3]

Example of four arithmetic operations


obj = {:a=>1, :b=>2, :c=>3}
obj2 = obj.map{|x, y| y*2 }

p obj2
#output
[2, 4, 6]

### Process the value of an object and retrieve it as an object How to process the value of an object and retrieve it as an object.

▼ Convert from array to symbol

Create [key, process] in the process result, Convert to a symbol with the to_h method.

python


obj = {:a=>1, :b=>2, :c=>3}
obj2 = obj.map{|x, y| [x, y*2]}

p obj2
#output
[[:a, 2], [:b, 4], [:c, 6]]

p obj2.to_h
#output
{:a=>2, :b=>4, :c=>6}

** ▼ Method chain ** It can be described simply by using a method chain.

python


obj = {:a=>1, :b=>2, :c=>3}
obj2 = obj.map{|x, y| [x, y*2]}.to_h

p obj2
#output
{:a=>2, :b=>4, :c=>6}

#### Convert from array to hash

Create [key, process] in the process result, to_h{|Variable 1,Variable 2| [Variable 1.to_s,processing]}Convert to hash with.

python


obj = {:a=>1, :b=>2, :c=>3}
 obj2 = obj.map{|x, y| [x, y*2]}.to_h{|v, w| [v.to_s, w]}

p obj2
#output
{"a"=>2, "b"=>4, "c"=>6}

### When there is one argument When there is one argument, the key / value set is extracted as one element.

When processed, KV pairs are processed as a set.

python


obj = {:a=>1, :b=>2, :c=>3}
obj2 = obj.map{|x| x*2 }

p obj2   
#output
[[:a, 1, :a, 1], [:b, 2, :b, 2], [:c, 3, :c, 3]]

Recommended Posts

[Ruby] How to use the map method. How to process the value of an object and get it by hash or symbol.
[ruby] How to assign a value to a hash by referring to the value and key of another hash
[Java] How to get the key and value stored in Map by iterative processing
How to retrieve the hash value in an array in Ruby
[Ruby] How to get the value by specifying the key. Differences between hashes, symbols and fetch
[Swift5] How to get an array and the complement of arrays
[Rails] How to use the map method
[Ruby] I want to extract only the value of the hash and only the key
[Ruby] How to use gsub method and sub method
Output of how to use the slice method
[Java] Output the result of ffprobe -show_streams in JSON and map it to an object with Jackson
[Ruby basics] How to use the slice method
Use the where method to narrow down by referring to the value of another model.
[Java] How to get the maximum value of HashMap
[Ruby] How to get the tens place and the ones place
How to request by passing an array to the query with HTTP Client of Ruby
How to use the getter / setter method (in object orientation)
[Ruby] How to retrieve the contents of a double hash
It is difficult to use the empty string or date of DBUnit, so fix it and use it.
How to specify an array in the return value / argument of the method in the CORBA IDL file
How to use the link_to method
How to use the include? method
How to use the form_with method
[Rails] How to get the URL of the transition source and redirect
[Ruby] How to use any? Method
[Java] How to search for a value in an array (or list) with the contains method
How to get the contents of Map using for statement Memorandum
Method to add the number of years and get the end of the month
How to use Ruby inject method
How to get the length of an audio file in java
How to increment the value of Map in one line in Java
Method to describe by dividing into multiple methods How to pass arguments How to use return value Method overload Pass by value and pass by reference
How to operate IGV using socket communication, and the story of making a Ruby Gem using that method
[Ruby] How to use is_a? Differences from kind_of? and instance_of ?. How to check the type and return a boolean value.
Get the type of an array element to determine if it is an array
[For Rails beginners] Summary of how to use RSpec (get an overview)
Android development, how to check null in the value of JSON object
Use MyBatis to get Map with key as identifier and value as Entity
How to create your own annotation in Java and get the value
[Java] How to use the toString () method
[Note] [Beginner] How to write when changing the value of an array element in a Ruby iterative statement
[Swift] How to get the number of elements in an array (super basic)
Use hashes well in Ruby to calculate the total amount of an order
graphql-ruby: How to get the name of query or mutation in controller Note
I get an error when I try to use "^" or "$" in ruby ​​regular expression
[Ruby] Learn how to use odd? Even? And count the even and odd numbers in the array!
[Ruby] Meaning of &. How to avoid the error when the receiver (object) is nil
Get the class name and method name of Controller executed by HandlerInterceptor of Spring Boot
[Ruby] How to calculate the total amount using the initialize method and class variables
How to convert a value of a different type and assign it to another variable
How to get an arbitrary digit from a number of 2 or more digits! !!
[Ruby on Rails] How to Japaneseize the error message of Form object (ActiveModel)
How to find the cause of the Ruby error
[Ruby] "Reference to object" and "Contents of variable"
How to get today's day of the week
How to use the replace () method (Java Silver)
[Ruby on Rails] How to use session method
[Java] How to get the authority of the folder
I want to get the value in Ruby
[Swift] If the support of the application is iOS 11 or later, it was not necessary to use Int and Int64 properly
How to write offline real time Implementation example by ruby and C99 of F04