ruby 文字列操作

本稿について

本稿はサイト運営者が学んだことなどを記したメモの内容です。
全てが正確な情報とは限りません。ご注意ください。また修正するべき点は適時修正していきます

検索

先頭から検索
str.index(“hoge”)

後ろから検索
str.rindex(“hoge”)

文字列を含んでいるか
str.include?(“hoge”)

指定の文字列から始まっているか?
str.start_with?('mf')

指定の文字列で終わる
str.end_with?(‘hoge’)

複数候補からの検索
/(id|mail_addressname|number)/ =~ str

["id", "mail_address", "number"].any? { |word| str.include?(word) }

indexの範囲から文字列を抽出する
str.slice(start_index..end_index)
=> “hogehoge"

削除

文字を指定した数だけ削除する
str.slice!(0,3)


指定した文字列を削除する
spliceだと元から削ってしまうので、一時的に不要な文字を取り出して使う時はdeleteの方がよい

str.slice!(‘hoge')

str.delete(‘hoge')

文字列間の空白以外の空白を削除
str.strip

[参考]


末尾の改行コードを削除する
str
=> "localhost\n"
str.chomp
=> "localhost"


文字列の分割
str = "hoge=fuga"
=> "hoge=fuga"
str.split("=")
=> ["hoge", "fuga"]

文字列の長さの確認
str.length

文字列のバイトサイズの確認
str.bytesize

文字列の固定
NUMBER = "1234".freeze

Dateを作成する
Date.strptime(date_str, '%Y/%m/%d')

こちらはruby2.5.0から
DateTime.strptime('2001-02-03T12:13:14Z').to_s

文字列をクラスシンボルとして扱う
model.constantize.new

文字列をシンボルに変換する
str.to_sym

文字列をメソッド名として処理する
column = str.to_sym
object.send(column)

ランダムな文字列を返す
require ‘securerandom'

SecureRandom.hex(8) #=> "e11663225ffdb50c"
SecureRandom.base64(8) #=> "cIvj9lXP/1M="
SecureRandom.random_bytes(8) #=> "\xF95\xFF\xCE\x96Ik\xC6"

数値のみ抜き出す
str.gsub(/[^0-9]+/, "")

複数行にわたって文字列を定義する
contents = <<-"EOS"
  <div>
    <h3>テスト</h3>
    <p>id: #{@user.id}</p>
    <p>ユーザー名: #{@user.name} 様</p>
    <p>email:  #{@user.email}</p>
  </div>
EOS

Back