44
47

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 5 years have passed since last update.

[Ruby] 便利な組み込みクラスのメソッド達(String編)

Last updated at Posted at 2014-01-06

概要

パーフェクトRubyを読んでいて便利だと思ったもの一覧です。

Enumerable編
http://qiita.com/kidachi_/items/a00558cfb0a6a3e23f4b
Array編
http://qiita.com/kidachi_/items/e9cb26c4e6cb36b70a1c
Hash編
http://qiita.com/kidachi_/items/651b5b5580be40ad047e

文字列の整形

strip

余分な空白を削除。

> "  Ruby \n\t ".strip
=> "Ruby"

squeeze

重複文字列の削除

> 'Ruuuubbbbyyyyy'.squeeze
=> "Ruby"

# 選択した文字のみ重複削除
> 'Ruuuubbbbyyyyy'.squeeze('ub')
=> "Rubyyyyy"

sub

あるパターンに最初にマッチした文字列を置換。

> 'Ruby is practical programming language!'.sub(/p.*?\s/, 'awesome ')
=> "Ruby is awesome programming language!"

gsub

マッチした文字列すべてを置換。

> 'Ruby is practical programming language!'.gsub(/p.*?\s/, 'awesome ')
=> "Ruby is awesome awesome language!"

# マッチした文字列はブロックに与えて操作することも出来る。
> 'Ruby is practical programming language!'.gsub(/p.*?\s/){|str| str.upcase}
=> "Ruby is PRACTICAL PROGRAMMING language!"

# マッチした文字列情報を$&で取得。
> 'Ruby is practical programming language!'.gsub(/p.*?\s/){ $&.to_s.upcase}
=> "Ruby is PRACTICAL PROGRAMMING language!"

split

特定の文字列をセパレータに指定して分割した要素を、配列として返却。

> str = 'Ruby, Python, Java'
> str.split(', ')
=> ["Ruby", "Python", "Java"]

# 正規表現も可
> str.split(/,\s/)
=> ["Ruby", "Python", "Java"]

# 第2引数を与えると、その数以上は分割しない。
> str.split(/,\s/, 2)
=> ["Ruby", "Python, Java"]

部分文字列の取得

slice

部分文字列の取得。

# 始点から終点を指定
> 'Ruby is my 1st language!'.slice(0..3)
=> "Ruby"

# 正規表現での指定も可能
> 'Ruby is my 1st language!'.slice(/[0-9]+/)
=> "1"

繰り返し処理

each_char

文字ごとの繰り返し

> 'Ruby'.each_char {|c| str << "#{c}!"}
> p str
"R!u!b!y!"

each_line

行ごとの繰り返し

> "Ruby\nis\ngood\nlanguage!".each_line { |line| puts line }
Ruby
is
good
language!

each_byte

バイトごとの繰り返し

> 'Ruby'.each_byte { |b| puts b}
82
117
98
121
44
47
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
44
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?