调用方法' count'返回错误的参数数量

时间:2017-07-27 12:44:55

标签: ruby

我有一个带两个参数的方法。 (max_length)的整数和(text)的字符串。如果文本中每个单词的字符数是> = max_length,我们会从数组中删除该单词。最后我们计算数组中剩余的单词。

我的方法很有效,直到text.count遇到'wrong number of arguments, given 0 expected 1+'

know这是因为我们还没有将任何参数传递给text.count,但我不想传递任何内容,因为我只想计算剩余的字数留在阵列中。

但是,如果我执行了一个简单的

示例
x = ["This", "Will", "Work"]
x.count => 3

为什么我不能在我的块中使用这个计数示例?

我做错了什么?

   def timed_reading(max_length, text)
     text.split.delete_if do |y|
       y.length >= max_length
       text.count
     end
   end

3 个答案:

答案 0 :(得分:2)

我认为这就是你想要做的事情

def timed_reading(max_length, text)
  text.split.delete_if { |y| y.length >= max_length }.count
end

你可以计算长度小于最大值的单词

text.split.count { |y| y.length < max_length }

答案 1 :(得分:1)

如果您返回的只是计数,则无需删除单词。您只需将count与块一起使用:

def timed_reading(max_length, text)
  text.split.count{|w| w.length < max_length}
end

答案 2 :(得分:0)

您在字符串count上调用text而不在数组上调用delete_if。您需要重新安排代码,以便在呼叫def timed_reading(max_length, text) short_words = text.split.delete_if do |y| y.length >= max_length end short_words.count end 电话时调用。像这样:

    let currentstoryboard = UIStoryboard()
相关问题