【问题标题】:how to Consider the alternatives of 'throw and catch'?如何考虑“投掷和接球”的替代方案?
【发布时间】:2014-11-28 15:43:45
【问题描述】:

我正在做以下 Ruby 教程http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/41-exceptions/lessons/93-throw-and-catch。其中一项练习要求我:

更改最后一个示例以从名为的方法返回找到的图块 而是搜索。搜索应该接收平面图作为参数。

练习类似于上一个示例(练习前),看起来像:

candy = catch(:found) do
    floor.each do |row|
    row.each do |tile|
        throw(:found, tile) if tile == "jawbreaker" || tile == "gummy"
    end
    end
end
puts candy

练习下面有个提示:

尝试将“catch”行替换为方法定义和 'throw' 行带有 'return'。

我这样做了:

candy = search do
    floor.each do |row|
    row.each do |tile|
      return tile if tile == "jawbreaker" || tile == "gummy"
    end
    end
end
puts candy

但收到错误。谁能告诉我如何做才能获得积极的结果。还有一个问题:为什么在 throw / catch 代码中有 catch(:found) 和不同的 throw(:found, tile)?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    更改最后一个示例,改为从名为 search 的方法返回找到的图块。搜索应该接收平面图作为参数。

    据我了解,练习是实现一种称为搜索的方法,该方法接收平面图作为参数。所以你需要实现一个叫做search的方法

    def search(floor)
    

    它应该返回结果给candy,所以调用代码应该是这样的:

    candy = search(floor)
    puts candy
    

    现在,剩下的就是实现方法体,它应该返回结果。为了返回正确的结果,row.each 应该在谓词 (tile == "jawbreaker" || tile == "gummy") 为 true 时立即停止。你可以用别的东西代替它。 find 返回匹配谓词的第一个元素:

    row.find { |tile| tile == "jawbreaker" || tile == "gummy" }
    

    我会将外部循环 (floor.each) 所需的更改留给 OP 作为练习。

    【讨论】:

      【解决方案2】:

      我的以下尝试通过了练习规范。

       def search( floor)
          floor.each do |row|
            row.each do |tile|
              return tile if tile == "jawbreaker" || tile == "gummy"
            end
          end
      end
      
      candy = ->(flr) {
         search(flr)
      }
      
      puts candy
      

      【讨论】:

        【解决方案3】:

        我没有看到你提到的提示,但我猜他们希望你试试这个:

        candy = floor.each do |row|
          row.each do |tile|
             return tile if tile == "jawbreaker" || tile == "gummy"
          end
        end
        puts candy
        

        供您接收LocalJumpError。因为你不能在这里使用return。你可以使用break,但它只会把你从内部循环中带出来,这就是为什么我们使用throw-catch来跳出嵌套循环。

        【讨论】:

          【解决方案4】:

          好的,我这样做了,它对我有用。如果你已经在 ruby​​ 中达到了这个程度,那么代码就很容易解释了

          floor = [["blank", "blank", "blank"],
               ["gummy", "blank", "blank"],
               ["blank", "blank", "blank"]]
          def search(floor)
          floor.each do |row|
          row.each do |tile|
            return tile if tile == "jawbreaker" || tile == "gummy"
          end
          end
          end
          
          candy = lambda {|floor| search(floor)}
          puts candy.call(floor)
          

          【讨论】:

            猜你喜欢
            • 2017-10-12
            • 2023-03-16
            • 2016-05-11
            • 1970-01-01
            • 2012-10-07
            • 2015-03-04
            • 1970-01-01
            • 2020-10-12
            • 2011-04-14
            相关资源
            最近更新 更多