1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

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

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"]

上記のような出力になる

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
Sign upLogin
1
Help us understand the problem. What are the problem?