【问题标题】:calling the method 'count' returns wrong number of arguments调用方法“count”返回错误数量的参数
【发布时间】:2017-07-27 12:44:55
【问题描述】:

我有一个带有两个参数的方法。 (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

【问题讨论】:

  • “我做错了什么?” - 你的计数在delete_if 的块中,它应该在外面。
  • 方法名称并没有让我觉得特别具有描述性。

标签: ruby


【解决方案1】:

我认为这就是你想要做的

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 }

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      您在字符串 text 上而不是在数组上调用 count。您需要重新排列您的代码,以便您根据 delete_if 调用的结果调用 count 。像这样的:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-07
        • 2018-07-07
        • 1970-01-01
        • 2019-02-08
        • 1970-01-01
        • 2014-07-04
        • 2014-11-01
        • 1970-01-01
        相关资源
        最近更新 更多