[Ruby] How to use arrays (personal memorandum)

1 minute read

Introduction

Summary about personal arrangement.

array definition

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]

Add element to array

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 an element at the specified position
array.insert(2, 5)
p array
=> [1, 2, 5, 3]

The insert method is convenient because it can be added at the specified position.

Delete array element

array = [1, 2, 3, 4, 5]

## Delete specified element
array.delete(4)
p array
=> [1, 2, 3, 5]

## Delete the first element
array.shift
p array
=> [2, 3, 4, 5]

## Delete 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 elements in the specified range
array.slice!(1, 3)
p array
=> [1, 5]

## Delete only true elements
array.select! {|n| n %2 == 0}
p array
=> [2, 4]

Delete only elements with ## false
array.reject! {|n| n %2 == 0}
p array
=> [1, 3, 5]

Array output

array = [1, 2, 3, 4, 5, 6, 7]

## Output at 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 elements with ## false
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

At the end

I think you can do basic things with this.

Tags:

Updated: