2012-07-16 37 views
2

我是Ruby编程的初学者。我的程序是给定字符串中单词长度的计数。但它显示了以下错误对于[0,0]未定义的方法'<':Array <NoMethodError>

未定义的方法 '<' 为[0,0]:数组

这里是我的代码

def even(words, n) 
    i = 0, m = 0 
    while i < n do 
     count = count + words[i].length 
     if count%2 == 0 then 
      m = m + 1 
     end 
     i = i + 1 
    end 
    return m 
end 
prinnt "Enter The String:" 
s = gets.chomp 
words = s.split() 
n = words.length 
x = even(words, n) 
puts x 
+1

用'words = s.split(“”)替换'words = s.split()',否则你的输入不会被字符分割 – krichard 2012-07-16 07:36:17

回答

0

试试吧

def even(words, n) 
    i = 0 
    m = 0 
    count = 0 
     while i < n do 
     count = count + words[i].length 
     if count%2 == 0 then m = m + 1 end 
     i = i + 1 
     end 
     return m 
     end 
     print "Enter The String:" 
     s = gets.chomp 
     words = s.split("") 
     n = words.length 
     #p n 
     x = even(words, n) 
     puts x 
1

我是这样想做它:

'this is a string'.split.select{ |w| w.size % 2 == 0 }.size # => 3 

申请gets

gets.chomp.split.select{ |w| w.length % 2 == 0 }.size 
1

其他人都已经给你解释的立即错误是在你的代码是什么。然而,更大的问题是你的代码不是惯用的Ruby代码。

惯用的代码会是这个样子:

puts gets.split.map(&:length).count(&:even?) 

而且,正如你所看到的,根本就没有办法,你可以甚至犯了一个错误,如您所做的一个。

相关问题