Just do IT

思うは招く

Ruby基礎問題100本ノック#3 文字列の各文字を数える

前回に引き続き、今度は単語ではなく文字の個数を数えてみる。

Ruby基礎問題100本ノック#2 文字列から単語をカウントしてハッシュで表現する - ゴリラよりオランウータン派

お題:文字列の各文字数を数えてハッシュで表現せよ

問題:文字列no pain no gainの各文字を数えよ(nが何個、oが何個など)

回答

string = 'no pain no gain'

def count_characters(string)
  ary = string.chars.reject { |i| i == ' '}
  @hash = Hash.new(0)
  ary.each { |c| @hash[c] += 1 }
end
count_characters(string)
p @hash
=> {"n"=>4, "o"=>2, "p"=>1, "a"=>2, "i"=>2, "g"=>1}

説明

前回とほぼ似たようなコードになった。

stringをcharsメソッドで各文字を配列に入れる。すると、こうなる。

ary = string.chars
 ["n", "o", " ", "p", "a", "i", "n", " ", "n", "o", " ", "g", "a", "i", "n"]

そう、空文字が入ってしまう。 なのでrejectメソッドを使い、ブロックの中で空文字を除去する処理をする。

ary = string.chars.reject { |i| i == ' '}

reject (Array) - Rubyリファレンス

delete_ifメソッドを使うこともできる。

ary = string.chars.delete_if { |i| i == ' '}

delete_if (Array) - Rubyリファレンス

反省

ary = string.chars.reject { |i| i == ' '}

この部分がもっとスマートに書けそうだが、わからず。

あとさすがに簡単だったかも。 朝イチだったので頭の体操に良かったと思おう。