Ruby:创建函数以查找具有最多重复字母的单词

时间:2014-11-13 23:31:56

标签: ruby

所以我收到了错误

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

非常感谢任何帮助

str = "one two three"
str = str.split(" ")
counter = 0
most_repeat_letter_word = nil

str.each do |char|
if char.length - char.split("").uniq!.length > counter 
most_repeat_letter_word = char
end
end
puts most_repeat_letter_word

2 个答案:

答案 0 :(得分:2)

你有两个问题:

  • counter未更新。
  • 如果没有进行任何更改,
  • Array#uniq会返回nil(正如许多&#34; bang&#34;方法一样),引发异常。使用uniq

这应该有效:

str = "one two three"
arr = str.split
counter = 0
most_repeat_letter_word = nil

arr.each do |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
  #=> three

编辑:唉,我误解了这个问题(即使我纠正了OP的刺伤),但我确实回答了另一个有趣的问题。 squeeze需要由uniq替换,正如@DarkMouse在答案中所做的那样。]

您可以在此处使用String#squeeze来删除重复的重复字符:

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

答案 1 :(得分:1)

您可以使用Enumerable的max_by函数找到它。

str = ["one", "two", "three"]
str.max_by{|s|s.chars.count - s.chars.uniq.count}
=> "three"