配列を操作する/要素の変更・追加・要素へのアクセス

スポンサーリンク
スポンサーリンク
ライフスタイル関連のコンテンツ
お金 | 仕事 | 勉強 | プライベート | 健康 |
プログラミング関連のコンテンツ
C言語/C++入門 | Ruby入門 | Python入門 | プログラミング全般
# 配列要素へのアクセス
w = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
p w[2]
p w[-2]
p w[1..4]
p w[1...4]
p w[1, 4]
puts
 
# 配列要素の値の変更
a = w
b = w.clone        # 別のオブジェクト
p a
a[0] = "Holiday"
a[1..5] = %w|Job School Test Shoping Party|
a[6] = "Holiday"
p a
p w     # 配列wも変更されている
p b        # cloneメソッドで作った配列bは元のまま
puts
 
# 配列の途中に要素を追加
b[0, 0] = "June:"
p b
b[3, 0] = "July:"
p b
 

スポンサーリンク

実行結果。

"Tuesday"
"Friday"
["Monday", "Tuesday", "Wednesday", "Thursday"]
["Monday", "Tuesday", "Wednesday"]
["Monday", "Tuesday", "Wednesday", "Thursday"]
 
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
["Holiday", "Job", "School", "Test", "Shoping", "Party", "Holiday"]
["Holiday", "Job", "School", "Test", "Shoping", "Party", "Holiday"]
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
 
["June:", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sat
urday"]
["June:", "Sunday", "Monday", "July:", "Tuesday", "Wednesday", "Thursday", "Frid
ay", "Saturday"]
スポンサーリンク
 
スポンサーリンク