序章

array は、elementsと呼ばれる値のリストを表すデータ構造です。 配列を使用すると、1つの変数に複数の値を格納できます。 In Ruby, arrays can contain any data type, including numbers, strings, and other Ruby objects. This can condense and organize your code, making it more readable and maintainable. All arrays are objects with their own methods you can call, providing a standardized way to work with data sets.

In this tutorial, you’ll create arrays, access the values they contain, add, modify, and remove elements in an array, and iterate through the elements in an array to solve more complex problems.

配列の作成

You’ll start by looking at how to create arrays in more detail. As an example, here is a list of various shark species. Without an array, you might store them in individual variables:

sharks.rb
shark1 = "Hammerhead"
shark2 = "Great White"
shark3 = "Tiger"

このアプローチは冗長であり、柔軟性が低いため、すぐに保守が困難になる可能性があります。 Adding another shark means you’d have to add, and track, an additional variable.

If you use an array, you can simplify this data. Rubyプログラムで配列を作成するには、角かっこを使用します:([]), and separate the values you want to store with commas:

sharks.rb
sharks = ["Hammerhead", "Great White", "Tiger"]

Instead of creating three separate variables, you now have one variable that contains all three sharks. In this example, you used square brackets — [] —配列を作成し、各エントリをコンマで区切ります。 If you had to add an additional shark, you would add another shark to the array rather than creating and managing a new variable.

配列全体を印刷できます print statement, which will display the array’s contents:

print sharks
Output
["Hammerhead", "Great White", "Tiger"]

各エントリが1つの単語である配列を作成する場合は、 %w{} 単語配列を作成する構文:

days = %w{Monday Tuesday Wednesday Thursday Friday Saturday Sunday}

これは、中括弧を使用して配列を作成するのと同じです。

days =  ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

ただし、 %w{} メソッドを使用すると、引用符とコンマをスキップできます。

Arrays are often used to group together lists of similar data types, but in Ruby, arrays can contain any value or a mix of values. This includes other arrays. 文字列を含む配列の例を次に示します。 nil 値、整数、および文字列の配列:

mixed_data.rb
record = [
    "Sammy",
    null,
    7,
    [
        "another",
        "array",
    ]
]

Now you’ll look at how to access data stored in arrays.

配列内のアイテムへのアクセス

特定のアイテム、または配列の要素にアクセスするには、そのインデックス、または配列内のその位置を参照します。 Rubyでは、インデックスはゼロから始まります。 In order to retrieve the first element from your sharks array, you append the element’s index to the variable using square brackets:

sharks.rb
sharks = ["Hammerhead", "Great White", "Tiger"]

The sharks 配列には3つの要素があります。 これは、の各要素の内訳です。 sharks 配列にはインデックスが付けられます。

ハンマーヘッド Great White
0 1 2

配列の最初の要素は Hammerhead、でインデックス付けされます 0. 最後の要素は Tiger、でインデックス付けされます 2. カウントは 0 in indices, which goes against the natural intuition to start counting at 1, so you’ll want to keep this in mind until it becomes natural.

Note: It might help you to think of the index as an offset, meaning the number of places from the start of the array. 最初の要素は先頭にあるため、そのオフセットまたはインデックスは次のようになります。 0. 2番目の要素は、配列の最初のエントリから1スポット離れているため、そのオフセットまたはインデックスは次のようになります。 1.

配列に含まれる要素の数は、 length 方法:

sharks.length
Output
3

のインデックスが sharks で開始 0 に行きます 2length プロパティは、配列内の要素の数を返します。 3. インデックスには全く関係ありません。

配列内の特定の要素のインデックス番号を知りたい場合(次のように) seahorse、 使用 index() 方法:

print sharks.index("Tiger")
Output
2

これは、そのテキストを含む最初の要素のインデックスを返します。 存在しない値など、インデックス番号が見つからない場合、コンソールは nil:

print sharks.index("Whale")
Output
nil

Rubyで配列の最後の要素を取得するには、インデックスを使用します -1:

print sharks[-1]
Output
"Tiger"

Rubyはまた提供します firstlast インデックスを使用せずに最初と最後の要素を取得するメソッド:

puts sharks.first
puts sharks.last
Output
"Hammerhead" "Tiger"

存在しないインデックスにアクセスしようとすると、 nil:

sharks[10]
Output
nil

Arrays can contain other arrays, which is called nested arrays. This is one way to model two-dimensional datasets in a program. ネストされた配列の例を次に示します。

nested_array = [
    [
        "salmon",
        "halibut",
    ],
    [
        "coral",
        "reef",
    ]
]

ネストされた配列の要素にアクセスするには、内部配列に対応する別のインデックス番号を追加します。 For example, to retrieve the value coral このネストされた配列から、次のステートメントを使用します。

print nested_array[1][0];
Output
coral

In this example, you accessed the array at position 1nested_array 配列を返した変数 ["coral", "reef"]. You then accessed the elements at position 0 その配列の "coral".

Now you’ll look at how to add elements to an array.

Adding Elements to Arrays

You have three elements in your sharks からインデックス付けされた配列 02:

sharks.rb
sharks = ["Hammerhead", "Great White", "Tiger"]

新しい要素を追加する方法はいくつかあります。 次のインデックスに値を割り当てることができます。この場合は、 3:

sharks[3] = "whale";

print sharks
Output
["Hammerhead", "Great White", "Tiger", "Whale"]

ただし、この方法ではエラーが発生しやすくなります。 要素を追加して誤ってインデックスをスキップすると、 nil 配列内の要素。

sharks[5] = "Sand";

print sharks;
Output
["Hammerhead", "Great White", "Tiger", "Whale", nil, "Sand"]

追加の配列要素にアクセスしようとすると、その値が返されます。 nil:

sharks[4]
Output
nil

配列内で次に使用可能なインデックスを見つけることはエラーが発生しやすく、余分な時間がかかります。 を使用してエラーを回避します push 配列の最後に要素を追加するメソッド:

sharks.push("thresher")
print sharks
Output
["Hammerhead", "Great White", "Tiger", "Whale", nil, "Whale", "Thresher"]

また、使用することができます << の代わりに構文 push 配列の最後に要素を追加するメソッド:

sharks << "Bullhead"
Output
["Hammerhead", "Great White", "Tiger", "Whale", nil, "Whale", "Thresher", "Bullhead"]

配列の先頭に要素を追加するには、 unshift() 方法:

sharks.unshift("Angel")
print sharks
Output
["Angel", "Hammerhead", "Great White", "Tiger", "Whale", nil, "Whale", "Thresher", "Bullhead"]

Now that you know how to add elements, you’ll look at removing them.

Removing Elements from Arrays

配列から特定の要素を削除するには、 delete また delete_at メソッド。 の中に sharks array, you created a nil 以前の配列要素。 You’ll get rid of it.

まず、配列内でその位置を見つけます。 あなたは使用することができます index それを行う方法:

print sharks.index(nil)
Output
4

次に、 delete_at インデックスの要素を削除します 4 配列を出力します。

sharks.delete_at(4)
print sharks
Output
["Angel", "Hammerhead", "Great White", "Tiger", "Whale", "Thresher", "Bullhead"]

The delete メソッドは、渡した値に一致する要素を配列から削除します。 削除するために使用します Whale 配列から:

sharks.delete("Whale")
print sharks;
Output
["Angel", "Hammerhead", "Great White", "Tiger", "Thresher", "Bullhead"]

The delete method will remove all occurrences of the value you pass, so if your array has duplicate elements, they’ll all be removed.

The pop method will remove the last element in an array:

sharks.pop
print sharks;
Output
["Angel", "Hammerhead", "Great White", "Tiger", "Thresher"]

Bullhead 配列の最後の要素として削除されました。 配列の最初の要素を削除するには、 shift 方法:

sharks.shift
print sharks
Output
["Hammerhead", "Great White", "Tiger", "Thresher"]

今回、 Angel 配列の先頭から削除されました。

を使用して popshift、配列の最初と最後から要素を削除できます。 使用する pop 配列内の残りの項目は元のインデックス番号を保持するため、可能な限り推奨されます。

The delete_at, pop、 と shift methods all change the original array and return the element you deleted::

sharks.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
deleted_at_element = sharks.delete_at(1)
popped_element = sharks.pop

puts "Deleted_at element: #{deleted_at_element}"
puts "Popped element: #{popped_element}"

puts "Remaining array: #{sharks}"
Output
Deleted_at element: Great White Popped element: Whale Remaining array: ["Hammerhead", "Tiger"]

これで、配列から要素を削除するいくつかの方法がわかりました。 Now you’ll look at how to modify the element you already have.

Modifying Existing Elements in Arrays

配列内の要素を更新するには、通常の変数の場合と同じように、代入演算子を使用して要素のインデックスに新しい値を割り当てます。

サメの新しい配列を考えると、 "Hammerhead" インデックスで 0, you’ll replace "Hammerhead""Angel":

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sharks[0] = "Angel"
print sharks;
Output
["Angel", "Great White", "Tiger", "Whale"]

正しい要素を確実に更新するには、 index 削除する要素を見つけるために行ったのと同じように、最初に要素を見つける方法。

Now you’ll look at how to work with all of the elements in the array.

Iterating Over Arrays

Rubyには、配列を反復処理するための多くの方法が用意されており、使用する各方法は、実行する作業の種類によって異なります。 Next you’ll explore how to iterate over an array and display each of its elements.

Rubyは for..in syntax:

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
for shark in sharks do
  puts shark
end

の各要素について sharks 配列、Rubyはその要素をローカル変数に割り当てます shark. You can then print the element’s value using puts.

見えない for..in しかし非常に頻繁に。 Ruby配列はオブジェクトであり、 each 要素を操作するためのメソッド。 The each メソッドはと同じように機能します for..in、ただし構文は異なります。

each.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sharks.each do |shark|
  puts shark
end

The each メソッドは、Rubyプログラミングでよく見られる構文を使用します。 引数としてRubyブロックを取ります。 ブロックは、メソッドのコンテキストで後で実行されるコードです。 この場合、コードは puts shark. The shark キーワード、パイプ文字で囲まれています(|)は、ブロックがアクセスする配列内の要素を表すローカル変数です。 Rubyは要素をこの変数に割り当て、ブロック内のコードを実行します。 The each method repeats this process for each element in the array:

Output
Hammerhead Great White Tiger Whale

ブロックが1行しかない場合、Ruby開発者が doend keywords with curly braces and condense the whole statement into a single line:

each.rb
...
sharks.each {|shark| puts shark }

これにより同じ結果が得られますが、使用するコード行が少なくなります。

The each_with_index メソッドも同様に機能しますが、配列要素のインデックスにアクセスすることもできます。 このプログラムは each_with_index 各要素のインデックスと値を出力するには:

each_with_index.rb
sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sharks.each_with_index do |shark, index|
  puts "The index is #{index}"
  puts "The value is #{shark}"
end

配列内の要素ごとに、Rubyはその要素を変数に割り当てます shark、および現在のインデックスをに割り当てます index 変数。 You can then reference both of those variables in the block.

Output
The index is 0 The value is Hammerhead The index is 1 The value is Great White The index is 2 The value is Tiger The index is 3 The value is Whale

You’ll iterate over the elements in an array often in your own programs, such as when you need to display the items from a database on a website, or when you’re reading lines from a file and processing their contents.

結論

配列は、Rubyでのプログラミングの非常に用途が広く基本的な部分です。 このチュートリアルでは、配列を作成し、個々の要素にアクセスしました。 また、配列内の要素を追加、削除、および変更しました。 最後に、配列を反復処理してその内容を表示する2つの方法を検討しました。これは、データを表示するための一般的な方法として使用されます。

チュートリアルRubyのデータ型についてを読んで、Rubyの他のデータ型について学習してください。