LoginSignup
0
0

More than 1 year has passed since last update.

formatメソッド(Ruby)

Posted at

Ruby3.1 Kernelモジュールformat

sprintf(string print formatted)フォーマット

formatの記述は『%指示子』が基本
指示子は、引数の型の解釈を示し、省略できない
・文字列を表す指示子:c,s,p
・整数を表す指示子:d,i,u,b,B,o,x,X
・浮動小数点数を表す指示子:f,g,e,E,G

#『%d又は%i』引数の数値を10進表現の整数として出力する
#整数でない場合はto_iと同規則で整数に変換する
format("%d",3.5)
#=> "3"
format("%d","0b1010") #0b(2進数)
#=> "10"

#『%s』は文字列を出力する
v = "moji"
5.times do |i|
  if i % 2 == 0
    puts format("文字列%d(%s)", i, v)
  end
end
#=>
"文字列0(moji)"
"文字列2(moji)"
"文字列4(moji)"
0
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
0
0