Ruby 开始和结束 block 的使用

标签 ruby

我已经编写了查找“Bottle 问题”的逻辑

  module Bottle
      class Operation
        def input
          puts 'Enter the number of bottles:'
          num = gets.chomp.to_i
          bottle_operation(num)
        end

        def bottle_operation(num)
          while (num < 10) && (num > 0)
            puts "#{num} bottles"
            num -= 1
            puts "One bottle open. #{num} bottles yet to be opened."
          end
      end
     end
     begin
       res = Operation.new
       res.input
     end
    end

我被要求在模块外使用 Begin 和 End block ,因为它的使用方式不正确。通过这样做我得到了以下错误

module Bottle
  class Operation
    def input
      puts 'Enter the number of bottles:'
      num = gets.chomp.to_i
      bottle_operation(num)
    end

    def bottle_operation(num)
      while (num < 10) && (num > 0)
        puts "#{num} bottles"
        num -= 1
        puts "One bottle open. #{num} bottles yet to be opened."
      end
  end
 end
end

begin
   res = Operation.new
   res.input
 end

ERROR `<main>': uninitialized constant Operation (NameError)

开始和结束 block 的正确使用方法是什么?如何以及在哪里使用

最佳答案

What is the correct way to use begin and end block? how and where to use

通常您根本不使用begin/end

您的代码中的错误是在模块 之外,类名必须是完全限定的。也就是说,以下内容将解决此问题:

- res = Operation.new
+ res = Bottle::Operation.new

begin/end 在以下情况下可能需要:

  • 您需要一个 block 在 while/until 内执行(感谢@Stefan);
  • 您想挽救一个异常;
  • 你想要一个 ensure block 。

总结:

begin
  puts "[begin]"
  raise "from [begin]"
rescue StandardError => e
  puts "[rescue]"
  puts e.message
ensure
  puts "[ensure]"
end

#⇒ [begin]
#  [rescue]
#  from [begin]
#  [ensure]

关于Ruby 开始和结束 block 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52269467/

相关文章:

ruby-on-rails - Product has_one状态和状态机作用于association的场景下如何为rspec测试添加种子数据

ruby - 从散列中删除空值

ruby - 在 rspec 中测试多步骤工作流程

ruby-on-rails - 在 Ruby 或 Ruby on Rails 中使用异常控制流是一种好习惯吗?

ruby - 如何检查类是否正确实例化

ruby - 如果路径中有西里尔字符,如何使用 require

ruby - ruby 和 irb 使用不同的模块搜索路径吗?

ruby-on-rails - 在任何来源中都找不到 rake-10.1.0

java - 测试方法 - Ruby/RSpec 与 Java/Mockito

ios - 在 iOS 11 中,键盘自动更正会创建无效的 UTF8