1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Arrayオブジェクトの基礎

Last updated at Posted at 2023-11-24

Arrayオブジェクトの基本的な使い方

Arrayオブジェクトとは配列とも呼ばれ、複数の順番に並べて保持できるオブジェクトです。

Arrayの基本的な使い方は以下の通りです。

array = [1,2,"aaa",4]

(ここで言うarrayはただの変数です。arrayじゃなくてdoraemonでも何でもOKです。)


実際に活用してみよう!

Arrayの中のひとつを参照したいとき

array = ["nobita", "sizuka", "suneo", "gian"]
puts array[gets.to_i]
#実行結果
2
suneo

要素を末尾に追加

Arrayオブジェクト << "要素"

array = ["nobita", "sizuka", "suneo", "gian"]
p array << gets.chomp
#実行結果
["nobita","sizuka","suneo","gian","doraemon"]

要素の削除

Arrayオブジェクト.delete_at(index)

array = ["nobita", "sizuka", "suneo", "gian", "doraemon"]
p array.delete_at(gets.to_i)
p array
#実行結果
["nobita","sizuka","suneo","gian"]

要素の変更

Arrayオブジェクト[index] = "変更したい要素"

array = ["nobita", "sizuka", "suneo", "gian"]
array[get.to_i] = gets.chomp
#実行結果
["nobita","sizuka","suneo","doraemon"]

補足

Arrayの値は0から順番に管理されています。
(1からではありませんのでご注意ください)
配列の","の後ろには半角スペースを入れるのがRubyのお作法です。
image.png

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?