0
0

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 1 year has passed since last update.

配列の最後の要素を取り出す

Posted at

<問題>下記の配列の最後の要素を取り出すには?

shiritori = ["りんご", "ゴリラ", "ラッパ", ...(途中は省略)... ,  "みかん"]
puts  [A]

<回答>

shiritori = ["りんご", "ゴリラ", "ラッパ", ...(途中は省略)... ,  "みかん"]
puts shiritori[shiritori.length - 1]

<解説>

この問題のポイントは配列の要素の数が分からないという点です。
最後の要素は[配列の要素数 - 1]で取得ができます。
そこでlengthメソッドを使います。lengthメソッドを使えば正確に配列の要素数がわかります。プログラムは0から始まるため、「-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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?