简体   繁体   English

[0,0]的未定义方法&#39;&lt;&#39;:Array <NoMethodError>

[英]Undefined method '<' for [0, 0] :Array <NoMethodError>

I am beginner of Ruby programming. 我是Ruby编程的初学者。 My program is count number of even length of words in a given string. 我的程序是计算给定字符串中单词的偶数长度。 But it's shows the following Error 但它显示以下错误

Undefined method '<' for [0, 0] :Array [0,0]的未定义方法'<':Array

Here is My code 这是我的代码

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

I think your problem is here 我想你的问题在这里

i = 0, m = 0

make it 做了

i = 0
m = 0

Edit: 编辑:

Also like Kai König said, if you call it like that it means 也像KaiKönig所说的那样,如果你这样称呼它意味着

" now's  the time".split        #=> ["now's", "the", "time"]

http://ruby-doc.org/core-1.9.3/String.html#method-i-split http://ruby-doc.org/core-1.9.3/String.html#method-i-split

Here's how I'd do it: 这是我的处理方式:

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

Applying to gets : 申请gets

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

The others have already explained to you what the immediate error is in your code. 其他人已经向您解释了代码中的立即错误。 However, the bigger problem is that your code is just not idiomatic Ruby code. 但是,更大的问题是您的代码不是惯用的Ruby代码。

Idiomatic code would look something like this: 成语代码看起来像这样:

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

And, as you can see, there is simply no way that you could even make a mistake such as the one you made. 而且,正如你所看到的,根本就没有办法,你甚至可以使一个错误,如您所做的一个。

Try it 试试吧

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM