Created
March 1, 2015 09:33
-
-
Save a13e/cd05238a29a57529bc8a to your computer and use it in GitHub Desktop.
パーフェクトRuby 5章 String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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