Help us understand the problem. What is going on with this article?

[Ruby]あまり見ないけどたまに便利なメソッド[String編]

More than 5 years have passed since last update.

sprintfのフォーマット文字列として扱う

"ID: %05d" % 321
# => "ID: 00321"

足したり掛けたりする

"ventra " * 2 + "space people"
# => "ventra ventra space people"

中央寄せ文字列を作る

"title".center(20)
# => "       title        "

" title ".center(20, "#")
# => "###### title #######"

左寄せ、右寄せも

"title".ljust(20, ".")
# => "title..............."

"title".rjust(20, ".")
# => "...............title"

一行毎に処理する

"abc\ndef\nxyz".each_line do |line|
  puts line
end

.linesでもいける。

"abc\ndef\nxyz".lines do |line|
  puts line
end

.split("\n").eachより手軽だけど、.each_line.linesに渡される行は改行コードが入ったままなのに注意。

IDをインクリメントする

"X1001".succ
# => "X1002"
"X9999".succ
# => "Y0000"

"A".succ
# => "B"
"Z".succ
# => "AA"

なんとなく、こうしたいんだろうなと思えるIDを作ってくれて便利。

連続した文字を縮める

"Woooooooooooow!".squeeze
# => "Wow!"

先頭の文字列が一致するかどうかを調べる

%w(F-14 A-10 F-18).each do |jet|
  puts "#{jet} is Fighter" if jet.start_with?("F-")
end
# => "F-14 is Fighter" "F-18 is Fighter"
nao58
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away