2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyで正規表現でmatch!!

Last updated at Posted at 2017-05-14

複数の候補での前方一致検索の作り方!

Usersテーブルから、頭文字で任意のユーザーを検索する方法。

  • フォームに複数入力された値を、それぞれ頭文字に持つ人を検索するコードを解説します。
  • まずソースを掲げ、その後解説します!
hoge.rb
input = "s t k"
inputs = input.split("").reject(&:blank?)
new_inputs = inputs.map {|ele| /^#{ele}/}
word = new_inputs.join("|")
reg = Regexp.new(word)
users = User.all
names = []
users.each do |user|
  name = user.name
  if name.match(reg)
  names << name
  end
end
  • 部分に分け解説します。
input = "s t k"
  • 今、誰かがsとtとkをスペースで区切ってフォームに入力しました。
  • この人はをsとtとkを頭文字に持つ人を検索しようとしています。
  • その情報を取得し、inputに代入しました。
inputs = input.split("").reject(&:blank?)
  • .split("")でinputは["s"," ","t"," ","k"]という配列に分割されます。
  • .reject(&:blank?)で上の配列から" "(スペース)を除きます。
  • つまり、inputs = ["s","t","k"]という風になります。
new_inputs = inputs.map {|ele| /^#{ele}/}
  • ["s","t","k"]の要素それぞれに^を足して、前方一致の形式にします。
  • これで、new_inputs =["^s","^t","^k"]という風になります。
word = new_inputs.join("|")
  • .join("|")で要素を結合します。
  • | で区切ることで、この後matchを使うときに^sか^kか^tのどれかとmatchすれば、trueが返ってくるようになります。
reg = Regexp.new(word)
  • 文字列を加工しできたwordを使い、正規表現オブジェクトを生成します。
  • matchの引数には、正規表現オブジェクトしかなれないためです。

-- 残りの処理は、usersテーブルから、全レコードを取得してきて、それをeachで回して、条件に合致するものを、抽出しているという形になります。

2
3
3

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?