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?

【Ruby初学者】Rubyのpartitionとカンマ付き代入について

Last updated at Posted at 2025-11-16

※つまづいた部分の備忘録としてまとめました。

Rubyのpartitionと「カンマ付き代入」がセットだとどう動くのか。勉強中に知った、混乱する挙動について。
以下のコードについて

a, = (1..5).partition(&:odd?)
p a

実行すると、以下になる

[1, 3, 5]

だけが出力される。
ここには Rubyのpartitionと並列代入の仕様が絡んでいる。

partition は「true の配列」「false の配列」を返す。まず、partitionは、Enumerableのメソッドで、ブロックが trueを返した要素の配列、ブロックがfalseを返した要素の配列の2つの配列を返すメソッド。

例として

(1..5).partition(&:odd?)

上記は、こうなる

[[1, 3, 5], [2, 4]]
  • 奇数(odd?) → [1,3,5]
  • 偶数 → [2,4]

a, = ...は「最初の要素だけ受け取る」構文
Rubyの並列代入では、

a, b = [10, 20]

のように複数変数へ一気に代入が可能。

ここでポイントは

a, = [10, 20]

のように 左辺に変数が1つだけで末尾にカンマを置くと、Rubyは 「最初の要素だけを代入し、残りを捨てる」 という動作をする。

a, = [[1, 3, 5], [2, 4]]
# a = [1, 3, 5]

まとめ

a, = (1..5).partition(&:odd?)

(1..5).partition(&:odd?)  [[1,3,5], [2,4]]
a, = ["奇数側", "偶数側"]
 a = [1, 3, 5]

という流れとなる。

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