Rubyの文字列操作
[履歴] [最終更新] (2014/02/03 10:26:53)
最近の投稿
注目の記事

置換

sample.rb

str = "This is a string."

str["is"] = "is also"  # 一致した最初の箇所を置換
p str

str[/this/i] = "That"  # 一致した最初の箇所を置換
p str

p str.gsub(/\s/, '_')  # 一致した箇所すべてを置換

str.gsub!(/\s/, '-')  # 破壊的
p str

p str.gsub(/(\w+)/) { $1[0].upcase + $1[1..-1] } # ブロック版gsub (最後に評価された式で置換)

p str.tr 'a-z', 'A-Z'  # a-zをA-Zで置換

出力例

$ ruby sample.rb 
"This also is a string."
"That also is a string."
"That_also_is_a_string."
"That-also-is-a-string."
"That-Also-Is-A-String."
"THAT-ALSO-IS-A-STRING."

結合

str = "This is a string."
p str + " That is also a string."  # 非破壊的

str << " That is also a string." # 破壊的
p str

繰り返し

sample.rb

str = "blah "
str *= 3
p str

出力例

$ ruby sample.rb 
"blah blah blah "

分割

sample.rb

str = "This is a string."
array = str.split(//)
p array

出力例

$ ruby sample.rb 
["T", "h", "i", "s", " ", "i", "s", " ", "a", " ", "s", "t", "r", "i", "n", "g", "."]

便利メソッド

sample.rb

str = sprintf(" This is a %s. ", "string")
p str.strip
p str.strip.reverse

出力例

$ ruby sample.rb 
"This is a string."
".gnirts a si sihT"

イテレータ

sample.rb

str,str2 = "this",""
str3 =<<EOS
First line.
Second line.
EOS

str.each_byte do |byte|
  str2 << byte-32
end

str2.each_char do |char| # 多倍長文字に対応
  p char.class # 長さ1のstring
  p char
end

str3.each_line do |line|
  p line
end

出力例

$ ruby sample.rb 
String
"T"
String
"H"
String
"I"
String
"S"
"First line.\n"
"Second line.\n"

ヒアドキュメント

sample.rb

#!/usr/bin/ruby
# -*- coding: utf-8 -*-
File.open("sample.txt", 'w'){|f|
  # 識別子の前に '-' を付与すると、
  f.puts <<-EOS
こんばんは、はじめまして。
今は #{Time.now} です。
  EOS
  # 識別子をインデントできる
}
puts `cat sample.txt`

実行例

$ ruby hoge.rb | nkf -s
こんばんは、はじめまして。
今は 2014-02-03 01:24:41 +0900 です。
関連ページ