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 5 years have passed since last update.

Rubyのシンタックス勉強用(push, shift, unshift)[RUBY技術者認定試験...問題16]

Posted at

基本説明

配列操作系のメソッド。push, shift, unshiftを一気に学べる良問があったので共有します。

メソッッド名 説明 戻り値 破壊的?
push 配列の 末尾 に引数を要素として追加 レシーバ自身 TRUE
shift 配列の最初の要素を削除し、その要素を返す。配列が空のときはnilを返す。 削除した要素 TRUE
unshift 配列の 先頭 に引数を要素として追加 レシーバ自身 TRUE

オブジェクト自身(レシーバ)の内容を変えてしまうものを破壊的メソッド。

例題

以下の出力結果は?

ary = %w(a b c d e)
ary.push(ary.shift)
ary.unshift(nil)
p ary

RUBY技術者認定試験 公式ガイド (ITpro BOOKs) 153p 問題16より抜粋

実行結果は以下でサクッと試せます

Online Ruby Editor and IDE - Fast, Powerful, Free - Repl.it

参考

正解

  • 例題: [nil, "b", "c", "d", "e", "a"]
ary = %w(a b c d e) # => ["a", "b", "c", "d", "e"]
ary.push(ary.shift) # => ["b", "c", "d", "e", "a"]
ary.unshift(nil) # => [nil, "b", "c", "d", "e", "a"]
p ary # => [nil, "b", "c", "d", "e", "a"]
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?