Hatena::Grouprubyist

てーげーRuby

2008-06-30

練習問題 文字列(前半)

| 17:09

(1) "ruby is an object oriented programming language"という

文字列があります。この文字列を使って次の処理を行ってください

(a) 文字列に含まれる各単語を要素とする配列を作ってください。

irb(main):041:0> "ruby is an object oriented programming language".split
=> ["ruby", "is", "an", "object", "oriented", "programming", "language"]

(b) (a)の配列をアルファベット順にソートしてください。

irb(main):042:0> "ruby is an object oriented programming language".split.sort
=> ["an", "is", "language", "object", "oriented", "programming", "ruby"]

(c) (a)の配列を大文字と小文字の区別をせずにアルファベット順に

ソートしてください。

irb(main):046:0> "ruby is an object oriented programming language".split.sort_by{|e| e.upcase}
=> ["an", "is", "language", "object", "oriented", "programming", "ruby"]

(d) すべての単語の先頭を大文字にして

"Ruby Is An Object Oriented Programming Language"

にしてください。

irb(main):050:0> "ruby is an object oriented programming language".split.map{|e| e.capitalize}.join(' ')
=> "Ruby Is An Object Oriented Programming Language"

(e) 文字列に含まれる文字とその数を次のような形式で表示させてください

(空白文字が6つ、'R'が1つ、'a'が4つ、'b'が……という意味です)

' ': ******

'R': *

'a': ****

'b': **

'c': *

...

irb(main):148:0> h = Hash.new
=> {}
irb(main):149:0>
irb(main):150:0* "ruby is an object oriented programming language".scan(/./).sort.each do |e|
irb(main):151:1*   unless h[e]
irb(main):152:2>      h[e] = 1
irb(main):153:2>   else
irb(main):154:2*      h[e]+=1
irb(main):155:2>   end
irb(main):156:1> end
=> [" ", " ", " ", " ", " ", " ", "a", "a", "a", "a", "b", "b", "c", "d", "e", "e", "e", "e", "g", "g", "g", "g", "i", "i", "i", "j", "l", "m", "m", "n", "n", "n", "n", "o", "o", "o", "p", "r", "r", "r", "r", "s", "t", "t", "u", "u", "y"]
irb(main):157:0>
irb(main):158:0* h.each do |k,v|
irb(main):159:1*  puts("'#{k}': #{'*'*v}")
irb(main):160:1> end
' ': ******
'l': *
'a': ****
'm': **
'b': **
'y': *
'n': ****
'c': *
'o': ***
'd': *
'p': *
'e': ****
'r': ****
'g': ****
's': *
't': **
'i': ***
'u': **
'j': *
=> {" "=>6, "l"=>1, "a"=>4, "m"=>2, "b"=>2, "y"=>1, "n"=>4, "c"=>1, "o"=>3, "d"=>1, "p"=>1, "e"=>4, "r"=>4, "g"=>4, "s"=>1, "t"=>2, "i"=>3, "u"=>2, "j"=>1}