4
\$\begingroup\$

Input

A list of words separated by any number of spaces.

Output

A horizontal ASCII art histogram, where the n-th line is composed by as many asterisks (*) as the n-th word is long.

Example usage

The > signals user input, you should not input it when testing the program.

> This is an example histogram of word length
****
**
**
*******
*********
**
****
******

> a aa aaa aaaa aaaaa
*
**
***
****
*****

> double space  example
******
*****
*******

The code

puts gets.chomp.split.map{|word| '*' * word.length}.join("\n")
\$\endgroup\$
5
\$\begingroup\$

Looks good. There's really not a lot to review. About the only thing I can think of is that I'd like a little breathing space in the block, i.e.

{ |word| "*" * word.length }

But that's about it :)

Of course, there are also other ways to go about this, for instance:

puts gets.chomp.gsub(/\S/, "*").gsub(/\s+/, "\n")

Not that that's necessarily any better.

\$\endgroup\$
  • \$\begingroup\$ Yup, not a lot of code to comment on, it was too easy of a problem :) (p.s. I find that regexes make this piece of code less clear) \$\endgroup\$ – Caridorc Sep 7 '15 at 12:26
  • \$\begingroup\$ @Caridorc Yeah, as mentioned, it's not better, just different. Personally, I'm quite fond of regexes, but you're right; in this case there's no need. I kind of like that there's no need to split and join - the string remains a string throughout. But that's about it. \$\endgroup\$ – Flambino Sep 7 '15 at 12:56
3
\$\begingroup\$

If you're going to just 'puts' this at the end, you don't need the join, as puts will automatically print each array element on its own line.

puts gets.chomp.split.map{|word| '*' * word.length}

An alternative way of doing this is with tr:

puts gets.chomp.split.map{|word| word.tr '^ ', '*'}

The arguments to tr say replace all non-space chars ('^ ') with '*'.

Because tr works on the string as a whole, you can factor out the map:

puts gets.chomp.tr('^ ', '*').split
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.