やりたいこと
- Rubyハッシュ(連想配列)のnilチェック
- 配列の部分一致検索
1. Rubyのハッシュ(連想配列)のnilチェック
- 最初はif文でnilチェックをやろうと思ったけど、Ruby2.3で導入された
dig()
を使う方が簡単だった
params.dig(:q, :name)
2. 配列の部分一致検索
search_text = '検索したい文字'
array.select { |e| e =~ %r{^.*#{search_text}.*} }
-
#{}
で囲うとで変数を入れられる -
%r{}
で正規表現オブジェクトを作成した場合、パターン内に「/」が含まれていてもエスケープは不要らしい。便利!
「もっとこうした方が楽だよ!」と言った知見があれば、コメントお待ちしてます