0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

配列の使い方(個人的な備忘録)

Last updated at Posted at 2020-08-30

はじめに

個人的な配列についてのまとめ。

配列の定義

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]

## 先頭に追加
array.unshift(10)
p array
=> [10, 1, 2, 3]

## 最後に要素を追加
array << 10
p array
=> [1, 2, 3, 10]

array.push(10)
p array
=> [1, 2, 3, 10]

## 指定した位置に要素の追加
array.insert(2, 5)
p array
=> [1, 2, 5, 3]

insertメソッドは指定位置に追加できるため便利。

配列の要素を削除

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

## 指定した要素の削除
array.delete(4)
p array
=> [1, 2, 3, 5]

## 先頭の要素を削除
array.shift
p array
=> [2, 3, 4, 5]

## 最後の要素を削除
array.pop
p array
=> [1, 2, 3, 4]

## 指定した位置の要素を削除
array.delete_at(2)
p array
=> [1, 2, 4, 5]

## 指定した範囲の要素の削除
array.slice!(1, 3) 
p array
=> [1, 5]

## trueの要素のみ残し、他を削除
array.select! { |n| n % 2 == 0 }
p array
=> [2, 4]

## falseの要素のみ残し、他を削除
array.reject! { |n| n % 2 == 0 }
p array
=> [1, 3, 5]

配列の出力

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

## 指定した位置の出力
puts array[0]
=> 1

puts array[5]
=> 6

## 指定した範囲の出力
puts array.slice(3, 4).join
=> 4567

## trueの最初の要素のみ出力
puts array.find { |n| n % 3 == 0 }
=> 3

## trueの最初の要素の位置を出力
puts array.find_index { |n| n % 3 == 0 }
=> 2

## trueの要素のみ出力
puts array.select { |n| n % 2 == 0 }.join
=> 246

## falseの要素のみ出力
puts array.reject { |n| n % 2 == 0 }.join
=> 1357

## false手前の要素を出力
puts array.take_while { |n| n < 5 }.join
=> 1234

## false以降の要素を出力
puts array.drop_while { |n| n < 5 }.join
=> 567

終わりに

基本的なことはこれでできると思います。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?