Ruby 配列内の値を偶数(奇数)に分けるサンプル

環境
Windows11 Pro 64bit
ruby 3.1.2p20

構文
偶数,奇数 = 配列.partition(&:even?)
配列内の値を偶数・奇数に分けるには、「partition(&:even?)」を使用します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cft = [21, 32, 43, 64, 65]
s, t = cft.partition(&:even?)
p s
p t
p cft
cft = [21, 32, 43, 64, 65] s, t = cft.partition(&:even?) p s p t p cft
cft = [21, 32, 43, 64, 65]

s, t = cft.partition(&:even?)

p s

p t

p cft

実行結果
[32, 64]
[21, 43, 65]
[21, 32, 43, 64, 65]

IT,Ruby

Posted by arkgame