Skip to content

Instantly share code, notes, and snippets.

@a13e
Created March 1, 2015 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a13e/cd05238a29a57529bc8a to your computer and use it in GitHub Desktop.
Save a13e/cd05238a29a57529bc8a to your computer and use it in GitHub Desktop.
パーフェクトRuby 5章 String
str = "Ruby is a programming language"
str.slice(5)#インデックスで位置から指定
=> "i"
str.slice(4, 6) #インデックス4から6文字取得する
=> " is a "
str.slice(4..6) # インデックスを範囲指定(4~6)
# slice!
irb(main):023:0> str.slice!("Ruby")
=> "Ruby"
irb(main):024:0> str
=> " is a programming language" #破壊的
#重複する文字列を削除
"aaaaaaaaaaaaaaaaoooooo".squeeze
=> "ao"
# 文字列置換
"24-1-356".sub(/[0-9]+/, "x") # 最初にマッチしたものを第2引数に置換
=> "x-1-356"
"24-1-356".gsub(/[0-9]+/, "x") # マッチしたものを第2引数に置換
=> "x-x-x"
# 文字列から配列へ変換
str = "Alice, Bob, Charlie"
str.split(', ') # 文字列で指定
=> ["Alice", "Bob", "Charlie"]
str.split(/,\s+/) # 正規表現で指定
=> ["Alice", "Bob", "Charlie"]
str.split(/,\s+/, 2) # 第2引数で指定した要素からは分割した要素にしない
=> ["Alice", "Bob, Charlie"]
# 文字列から文字の配列
"Ruby".split(//)
=> ["R", "u", "b", "y"]
"Ruby".each_char.to_a
=> ["R", "u", "b", "y"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment