I will make a note of the basic methods used in Ruby arrays.
version
ruby 2.6.5p114
First, prepare an appropriate array
$ animals = ["dog", "cat", "rabbit"]
=> ["dog", "cat", "rabbit"]
$ animals.push('bear')
=> ["dog", "cat", "rabbit", "bear"]
$ animals.unshift('monkey')
=> ["monkey", "dog", "cat", "rabbit", "bear"]
$ animals
=> ["monkey", "dog", "cat", "rabbit", "bear"]
$ animals.pop
=> "bear"
$ animals.shift
=> "monkey"
$ animals
=> ["dog", "cat", "rabbit"]
['dog',nil, 0, false,''].compact
=> ["dog", 0, false, ""]
["dog", "cat", "rabbit", "dog"].uniq
=> ["dog", "cat", "rabbit"]
$ animals = ["dog", ["cat",["rabbit, bear"]]]
=> ["dog", ["cat", ["rabbit, bear"]]]
$ animals.flatten
=> ["dog", "cat", "rabbit, bear"]
$ animals = [[1,2,3],["dog","cat","rabbit"]]
=> [[1, 2, 3], ["dog", "cat", "rabbit"]]
$ animals.transpose
=> [[1, "dog"], [2, "cat"], [3, "rabbit"]]
$ num = [1,2,3]
=> [1, 2, 3]
$ animals = ["dog","cat","rabbit"]
=> ["dog", "cat", "rabbit"]
$ num.zip(animals)
=> [[1, "dog"], [2, "cat"], [3, "rabbit"]]
["dog", "cat", "rabbit"].size
=> 3
[1,2,3].sum
=> 6
[3,1,2].sort
=> [1, 2, 3]
[1,2,3].reverse
=> [3, 2, 1]
[1,2,3].shuffle
=> [2, 1, 3]
[1,2,3].sample
=> 3
[1,2,3].sample
=> 1
["dog", "cat", "rabbit"].join
=> "dogcatrabbit"
["dog", "cat", "rabbit"].join('When')
=> "dog, cat and rabbit"
num = [1,2,3,4,5,6]
=> [1, 2, 3, 4, 5, 6]
num.select {|n| n % 2 == 0}
=> [2, 4, 6]
> num
=> [1, 2, 3, 4, 5, 6]
num.reject { |n| n % 2 == 0 }
=> [1, 3, 5]
Recommended Posts