所以我得到了错误
#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
最佳答案
你有两个问题:
counter
未更新。- Array#uniq如果未进行任何更改(与许多“bang”方法一样),则返回
nil
,引发异常。使用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"
关于Ruby:创建函数来查找重复字母最多的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26920441/