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)
python
range = 1..3
range2 = range.map{|x| x*2 }
p range2
#output
[2, 4, 6]
1D
arr = [1, 2, 3]
arr2 = arr.map{|x| x*2 }
p arr2
#output
[2, 4, 6]
[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]]
[[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]]]
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)
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
obj = {:a=>1, :b=>2, :c=>3}
obj2 = obj.map{|x, y| x*2 }
NoMethodError (undefined method `*' for :a:Symbol)
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]
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}
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}
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 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