0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

サイバーウェーブAdvent Calendar 2019

Day 22

文字列の空白や改行の削除まとめ

Last updated at Posted at 2019-12-15

Ruby技術者認定試験のシルバーで狙われる、空白や改行の削除をまとめてみた。

  • chomp
  • chop
  • strip
  • lstrip
  • rstrip
a = "\n \r abc \n \r"

a.chomp
=>"\n \r abc \n " #空白が残っている
a.chomp.chomp.chomp.chomp.chomp
=>"\n \r abc \n "

a.chop
=>"\n \r abc \n "
a.chop.chop.chop.chop.chop
=> "\n \r ab"

a.strip
=> "abc"
a.strip.strip.strip.strip.strip
=> "abc"

a.lstrip
=> "abc \n \r"
a.lstrip.lstrip.lstrip.lstrip.lstrip
=> "abc \n \r"

a.rstrip
=>"\n \r abc"
a.rstrip.rstrip.rstrip.rstrip.rstrip
=>"\n \r abc"

またそれぞれ!をつけると破壊メソッドになる

追記
"\r", “\r\n”, “\n”は改行コード1文字とみなされるので

p ["foo\r\n", "bar\n", "baz\n\r"].map {|i| i.chomp }
 => ["foo", "bar", "baz\n"]

上記のような出力になる

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?