3
2

More than 3 years have passed since last update.

【Ruby】配列のnilチェック+部分一致検索

Last updated at Posted at 2019-11-29

やりたいこと

  1. Rubyハッシュ(連想配列)のnilチェック
  2. 配列の部分一致検索

1. Rubyのハッシュ(連想配列)のnilチェック

  • 最初はif文でnilチェックをやろうと思ったけど、Ruby2.3で導入されたdig()を使う方が簡単だった
params.dig(:q, :name)

2. 配列の部分一致検索

search_text = '検索したい文字'
array.select { |e| e =~ %r{^.*#{search_text}.*} }
  • #{}で囲うとで変数を入れられる
  • %r{}で正規表現オブジェクトを作成した場合、パターン内に「/」が含まれていてもエスケープは不要らしい。便利!

「もっとこうした方が楽だよ!」と言った知見があれば、コメントお待ちしてます

参考サイト

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2