user4274735
user4274735

Reputation: 31

letter count in a string, Ruby

A silly question. I have a piece of code which counts letters appearances in a string lower case and uppercase letters as one. But it returns the hash keys in lower case. I would like to ask how can I make the hash keys return as uppercase letters? And also is there an easy way to put a line between each key? Thank you in forward!

downcase.scan(/\w/).inject(Hash.new(0)) {|h, c| h[c] += 1;h}

Upvotes: 1

Views: 1167

Answers (2)

Mohamad
Mohamad

Reputation: 35349

Use upcase first if you want the letters in uppercase.

Use each_with_object instead of inject. inject returns the result of the block and you have to explicitly return the hash in the end. each_with_object automatically returns the initial hash.

string = "Hello hElLo"
hash = string.upcase.scan(/\w/).each_with_object(Hash.new(0)) do |char, hash|
  hash[char] += 1
end
puts hash
# => {"H"=>2, "E"=>2, "L"=>4, "O"=>2}

To output individual letters and their count on a line each, iterate the hash:

hash.each do |key, value|
  puts "#{key} => #{value}"
end

# H => 2
# E => 2
# L => 4
# O => 2

Upvotes: 1

Hetal Khunti
Hetal Khunti

Reputation: 807

use upcase instead of downcase

 > string = "HellO hElLo"
 => "HellO hElLo" 

 > string.upcase.scan(/\w/).inject(Hash.new(0)) {|h, c| h[c] += 1;h}
 => {"H"=>2, "E"=>2, "L"=>4, "O"=>2} 

Upvotes: 3

Related Questions