A summary of personal arrays.
array = []
array1 = [1, 2, 3, 4, 5]
array2 = ["A", "B", "C"]
array3 = (1..5).to_a
=> [1, 2, 3, 4, 5]
array4 = ("a".."c").to_a
=> [a, b, c]
array = [1, 2, 3]
##Add to the beginning
array.unshift(10)
p array
=> [10, 1, 2, 3]
##Add element at the end
array << 10
p array
=> [1, 2, 3, 10]
array.push(10)
p array
=> [1, 2, 3, 10]
##Add element at specified position
array.insert(2, 5)
p array
=> [1, 2, 5, 3]
It is convenient because the insert method can be added at the specified position.
array = [1, 2, 3, 4, 5]
##Delete the specified element
array.delete(4)
p array
=> [1, 2, 3, 5]
##Remove the first element
array.shift
p array
=> [2, 3, 4, 5]
##Remove last element
array.pop
p array
=> [1, 2, 3, 4]
##Delete the element at the specified position
array.delete_at(2)
p array
=> [1, 2, 4, 5]
##Delete a specified range of elements
array.slice!(1, 3)
p array
=> [1, 5]
##Delete only true elements
array.select! { |n| n % 2 == 0 }
p array
=> [2, 4]
##Delete only false elements
array.reject! { |n| n % 2 == 0 }
p array
=> [1, 3, 5]
array = [1, 2, 3, 4, 5, 6, 7]
##Output at the specified position
puts array[0]
=> 1
puts array[5]
=> 6
##Output in the specified range
puts array.slice(3, 4).join
=> 4567
##Output only the first element of true
puts array.find { |n| n % 3 == 0 }
=> 3
##Output the position of the first element of true
puts array.find_index { |n| n % 3 == 0 }
=> 2
##Output only true elements
puts array.select { |n| n % 2 == 0 }.join
=> 246
##Output only false elements
puts array.reject { |n| n % 2 == 0 }.join
=> 1357
##false Output the previous element
puts array.take_while { |n| n < 5 }.join
=> 1234
##Output elements after false
puts array.drop_while { |n| n < 5 }.join
=> 567
I think you can do the basics with this.
Recommended Posts