LoginSignup
0
0

Ruby silverの模擬問題を抜粋して解説をしていきます。

下記コードの実行結果を4択から選ぶ問題になっています。

a = [2, 3, 6, 8, 12].map{ |d| d / 3 }
print a

1.[0, 1, 2, 2, 4]
2.[2, 3, 6, 8, 12]
3.[3, 6, 12]
4.エラーになる

まず、'.map'メソッドは元の配列の要素を変換した新しい配列を作成するメソッドになっています。
'.map'公式リファレンス

ブロック内にある'|d|'は'.map'メソッドが各要素を順番に参照するための変数になっています。

配列内にある各要素を3で割った結果を新しい配列に格納をするようになっています。

2/3 = 0.66...
3/3 = 1.0
6/3 = 2.0
8/3 = 2.66...
12/3 = 4
→[0,1,2,2,4] という配列が作られる。

最後に変数'a'を'print.a'で配列をコンソールに表示するように指示をしています。

print a
[0,1,2,2,4]

最終的に、1番が解答になります。

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