よく忘れるRubyの基本的記法

かきかけ

個人用メモ。

Symbol

Symbolの配列

%i(a b) # [:a, :b]

String

1文字

?a # "a"

Array

積集合
[1, 3, 5, 7, 9] & [1, 2, 3, 4, 5]   # [1, 3, 5]
headとtailに分解
head, *tail = [1, 2, 3]
head  # 1
tail  # [2, 3]
zip, transpose
[1, 2, 3].zip [4, 5, 6] # [[1, 4], [2, 5], [3, 6]]
arr1, arr2 = [[1, 4], [2, 5], [3, 6]].transpose
arr1   # [1, 2, 3]
arr2   # [4, 5, 6]
組み合わせ
[1, 2, 3, 4].combination(2).sort_by{|item| [item[0], item[1]]}
# combinationは順番保証しないことになっているので適宜sort_by

Enumerable

each_slice

(1..7).each_slice(3).to_a # [[1, 2, 3], [4, 5, 6], [7]]