Wednesday 15 September 2010

Ruby: Create function to find the word with most repeated letters -



Ruby: Create function to find the word with most repeated letters -

so i'm getting error

#test.rb:5:in `block in <main>': undefined method `length' nil:nilclass (nomethoderror) #from test.rb:4:in `each' #from test.rb:4:in `<main>'

any help much appreciated

str = "one 2 three" str = str.split(" ") counter = 0 most_repeat_letter_word = nil str.each |char| if char.length - char.split("").uniq!.length > counter most_repeat_letter_word = char end end puts most_repeat_letter_word

you have 2 problems:

counter not beingness updated. array#uniq returns nil if no alter made (as many "bang" methods), raising exception. utilize uniq.

this should work:

str = "one 2 three" arr = str.split counter = 0 most_repeat_letter_word = nil arr.each |w| candidate = w.length - w.split('').uniq.length if candidate > counter most_repeat_letter_word = w counter = candidate end end puts most_repeat_letter_word #=> 3

edit: alas, misread question (even though corrected op's stab), did reply interesting question. squeeze needs replace uniq above, @darkmouse did in answer.]

you can utilize string#squeeze advantage here, remove duplicate repeated characters:

str = "three blind mice, see how run." str.split.max_by { |w| w.size-w.downcase.squeeze.size } #=> "three"

ruby

No comments:

Post a Comment