覚えておくと便利な Array のメソッド

いつも「何かそういうメソッドあったはず」と思ってるりまを調べなおすことになるのでメモ。

Enumerable#each_cons

  • 順番に n 個ずつ取り出す。
marunouchi = ['方南町', '中野富士見台', '中野新橋', '中野坂上']
marunouchi.each_cons(2).to_a
# >> [["方南町", "中野富士見台"],
# >>  ["中野富士見台", "中野新橋"],
# >>  ["中野新橋", "中野坂上"]]

Array に経路が入っていて from-to を順番に取り出す場合などに便利。

Enumerable#each_slice

  • n 個ずつに分割して取り出す。
ls = ['bin', 'dev', 'etc', 'home', 'lib', 'proc', 'tmp', 'usr', 'var']
ls.each_slice(4).to_a
# >> [["bin", "dev", "etc", "home"],
# >>  ["lib", "proc", "tmp", "usr"],
# >>  ["var"]]

Array の内容を n 個ずつ処理したい場合に便利。

Array#combination

  • Array から n 個選ぶ組み合わせ。
(1..8).to_a.combination(2).to_a
# >> [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [1, 8],
# >>  [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8],
# >>  [3, 4], [3, 5], [3, 6], [3, 7], [3, 8], 
# >>  [4, 5], [4, 6], [4, 7], [4, 8],
# >>  [5, 6], [5, 7], [5, 8],
# >>  [6, 7], [6, 8],
# >>  [7, 8]]

上記は連勝複式の組み合わせ。*1
三連複なら combination(3)
ワイドなら combination(3).map{|i|i.combination(2)}

Array#product

  • 複数の Array の組み合わせ。
dice = (1..6).to_a
dice.product(dice)
# >> [[1, 1],  [1, 2],  [1, 3],  [1, 4],  [1, 5],  [1, 6],
# >>  [2, 1],  [2, 2],  [2, 3],  [2, 4],  [2, 5],  [2, 6],
# >>  [3, 1],  [3, 2],  [3, 3],  [3, 4],  [3, 5],  [3, 6],
# >>  [4, 1],  [4, 2],  [4, 3],  [4, 4],  [4, 5],  [4, 6],
# >>  [5, 1],  [5, 2],  [5, 3],  [5, 4],  [5, 5],  [5, 6],
# >>  [6, 1],  [6, 2],  [6, 3],  [6, 4],  [6, 5],  [6, 6]]

サイコロを 2 個振ったときの組み合わせを作る場合などに便利。
サイコロを 3 個振ったときは dice.product(dice, dice)*2

ありがちな名字の Array と 名前の Array を用意して、架空の氏名を生成したり。
sei.product(mei)

*1:競馬やらないので間違ってたらゴメン。

*2:そこから ひとつ取り出すなら [rand(6)+1, rand(6)+1, rand(6)+1] で済むんだけど。