0
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?

More than 3 years have passed since last update.

【Ruby・初心者】二次元配列とは・ループを使った処理自分用

Last updated at Posted at 2020-05-05

##二次元配列とは?
配列の中に配列を作ること。

##Array.newメソッド
配列を作成できる。

###要素が5こ、初期値が1という配列を作成する。

n = Array.new(5,1)
p n  # >= [1,1,1,1,1]

###Array.newメソッドとmapメソッドの組み合わせ
要素が5こ、[7,7,7,7]という配列を要素にする。

つまり、
・要素は5こ。
・配列の中の配列の数が4こ
・配列の中の配列の値は4。

 n = Array.new(5).map{Array.new(4,7)}
 p n  #=<[[7, 7, 7, 7], [7, 7, 7, 7], [7, 7, 7, 7], [7, 7, 7, 7], [7, 7, 7, 7]] 

※Array.new(5){ Array.new(4, 7) }と.mapを省略することも可能です。

##each_with_indexメソッド

enemies = ["スライム", "モンスター", "ゾンビ", "ドラゴン", "魔王"]
enemies.each_with_index do |e,i|
    puts "#{i}番目の#{e}が現れた!"
end

##mapメソッド

新しい配列を作るメソッド。

numbers = [12, 34, 56, 78, 90]
numbers2 =numbers.map do |item|
    item * 3  #各要素を3倍にして新しい配列を作成する。
end
p numbers2 #>=[36,102,168,234,270]
0
1
2

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