LoginSignup
1
0

More than 1 year has passed since last update.

【Ruby のまずいコード】数字を削除

Last updated at Posted at 2021-12-10

お題

引数として与えられた文字列中の半角数字を削除した文字列を返すメソッドを定義してください。

コード

def delete_digits(str)
  str.gsub(/\d/, "")
end

改善

このコードは特別まずいというほどではありませんが,決まった文字を削除するなら専用のメソッド String#delete があります。
これを用いると

def delete_digits(str)
  str.delete("0-9")
end

と書けます。こちらのほうがシンプルですし,速度もかなり上です。

なお,数字以外を削除する場合は delete("^0-9") と書けます。

1
0
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
1
0