Open5
Rubyの便利なメソッドなどをメモする

Array
compact
[1, nil, 2, nil, 3].compact
# => [1, 2, 3]
uniq
[1, 2, 2, 3, 1].uniq
# => [1, 2, 3]
flatten
[1, [2, [3, 4]], 5].flatten
# => [1, 2, 3, 4, 5]

nil
nil?
user.nil?
&.
user&.name
# optional chain
fetch
user.fetch(:name, 1)
# :nameがnilまたは未定義なら1を返す

ActiveRecord
pluck
User.pluck(:id, :email)
# [[1, "alice@example.com"], [2, "bob@example.com"]]
distinct
User.select(:role).distinct
# 重複を排除

ActiveSupport
present?
user.name.present?
# nil、false、空文字、空配列などを 「空」かどうか判定し、空でなければ true。
blank?
user.email.blank?
# nil、false、空文字列、空配列、空ハッシュなど 「中身がない」 場合に true。
presence
user.name.presence
# 空なら nil を返す、そうでなければその値を返す。
try
user.try(:profile).try(:bio)
# &. で良い?
in?
1.in?([1, 2, 3])
# true
deep_merge
{ a: { x: 1 } }.deep_merge({ a: { y: 2 } })
# { a: { x: 1, y: 2 } }
except
params.except(:token)
# 指定したキーを除く
slice
params.slice(:id, :name)
# 指定したキーだけ抜き出す

Object
dig
data = { user: { profile: { name: "Alice" } } }
data.dig(:user, :profile, :name)
# => "Alice"
freeze
name.freeze
name << " Smith"
# => FrozenError: can't modify frozen String