LoginSignup
0
0

More than 3 years have passed since last update.

【Ruby】文字の置き換えメソッド

Posted at

【コード】

S = "oishiyo"

def slug (s)
 puts s.gsub(/[oi]/,"o" => "0", "i" => "1")
end
slug(S)

【出力結果】

01sh1y0

【解説】
ハッシュを使って、指定の文字を置き換えるメソッドです。
今回はネットスラングLeetの中から"o"と"i"を抜粋して"oishiyo"を置き換えてみます。

変数Sに変換したい文字を代入します。
標準入力から取得したい場合は

S = gets

となります。

slugメソッドを定義、実引数(S)に変数Sを代入し、仮引数(s)へ渡します。
変数sの後に

s.gsub(/[oi]/,"o" => "0", "i" => "1")

このように、[]の中に置き換えたい文字を入れ、 => を使ってそれぞれ置き換えていきます。

ここでは、oを0に、iを1に、という具合です。

最後にputsで出力処理をして、実行します。

0
0
2

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