user4274735
user4274735

Reputation: 31

Iteration hash Ruby

I have this half working half broken code here.

hash = upcase.scan(/\w/).each_with_object(Hash.new(0)) do |char, hash|
  hash[char] += 1
end 
hash.each do |key, value|
  puts "#{key}: #{value.times{print"x"}}" 
end

Which returns something like this.

xH: 1
xE: 1
xxL: 2
xO: 1

=> {"H"=>1, "E"=>1, "L"=>2, "O"=>1}

My question how can I make the code print out the "x"'s after

#{key}:

instead of the number.

And also I like to know how is it possible to return nothing instead of the last line?

=> {"H"=>1, "E"=>1, "L"=>2, "O"=>1}

Thank you for your help!

Upvotes: 0

Views: 61

Answers (1)

Cristian Lupascu
Cristian Lupascu

Reputation: 40506

Change the line

puts "#{key}: #{value.times{print"x"}}" 

to

puts "#{key}: #{'x' * value}" 

It works, because in Ruby String * int will repeat the String int times.

In your version of the code, the print ... was evaluated (and printed to the console) before the puts got to display anything, and that's why you got that seemingly weird behavior.

Upvotes: 3

Related Questions