5-2-3 文字列の整形

In [2]:
str = " hi \t"

p str.strip
p str.rstrip
p str.lstrip
"hi"
" hi"
"hi \t"
Out[2]:
"hi \t"
In [3]:
"hi    \n\n".chomp
Out[3]:
"hi    \n"
In [4]:
'Users'.chop
Out[4]:
"User"
In [7]:
"foo.".sub(/\.$/,'')
Out[7]:
"foo"
In [9]:
"foo."[0...-1]
Out[9]:
"foo"
In [10]:
'yahoooooooooooooooooo'.squeeze
Out[10]:
"yaho"
In [11]:
'aabbbccdd'.squeeze('abc')
Out[11]:
"abcdd"
In [12]:
'aabbbccdd'.squeeze('a-c')
Out[12]:
"abcdd"
In [14]:
'aabbbccdd'.squeeze('^a')
Out[14]:
"aabcd"
In [16]:
'      aabb'.squeeze("\s")
Out[16]:
" aabb"
In [17]:
'      aabb'.squeeze('\s')
Out[17]:
"      aabb"
In [18]:
"\s"
Out[18]:
" "
In [21]:
p 'ABC'.downcase
p 'abc'.upcase
p 'Abc'.swapcase
p 'tiTle'.capitalize
"abc"
"ABC"
"aBC"
"Title"
Out[21]:
"Title"
In [24]:
'55-9-7-24'.sub(/[0-9]+/, 'x')
Out[24]:
"x-9-7-24"
In [25]:
'55-9-7-24'.gsub(/[0-9]+/, 'x')
Out[25]:
"x-x-x-x"
In [26]:
'55-9-7-24'.gsub(/[0-9]+/) {|str| str.to_i.succ}
Out[26]:
"56-10-8-25"
In [27]:
1.succ
Out[27]:
2
In [28]:
1.pred
Out[28]:
0
In [31]:
'55-9-7-24'.gsub(/([0-9]+)/) { $1.to_i.succ }
Out[31]:
"56-10-8-25"
In [32]:
str = ' hi '
p str.strip!

p str.strip!
"hi"
nil
In [33]:
p 'dam'.reverse
p 'ダムダムダムダムダム'.reverse
"mad"
"ムダムダムダムダムダ"
Out[33]:
"ムダムダムダムダムダ"

str = 'dam' str.reverse! str

5-2-4 配列への変換

In [35]:
str = 'America, Briten, Canada'

p str.split(',')
p str.split(/,\s+/)
["America", " Briten", " Canada"]
["America", "Briten", "Canada"]
Out[35]:
["America", "Briten", "Canada"]
In [37]:
str.split(/,\s+/, 2)[1]
Out[37]:
"Briten, Canada"
In [38]:
'Alice'.split(//)
'Alice'.each_char.to_a
Out[38]:
["A", "l", "i", "c", "e"]

'Alice'.each_byte.to_a

5-2-5 繰り返し処理

In [41]:
'ブフー'.each_char{|c| p c}
"ブ"
"フ"
"ー"
Out[41]:
"ブフー"
In [43]:
"Alice\nBob\nCarrot".each_line{|line| p line}
"Alice\n"
"Bob\n"
"Carrot"
Out[43]:
"Alice\nBob\nCarrot"
In [45]:
$/
Out[45]:
"\n"
In [48]:
"Alice\tBob\tCarrot".each_line("\t"){|line| p line}
"Alice\t"
"Bob\t"
"Carrot"
Out[48]:
"Alice\tBob\tCarrot"

次回は「5-2-6 エンコーディングの扱い」から