繁体   English   中英

Ruby Begin和End Block用法

[英]Ruby Begin and End Block usage

我写了逻辑来找到“瓶子的问题”

  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块,因为它的使用方法不正确。 通过这样做我得到以下错误

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

错误`<main>':未初始化的常量操作(NameError)

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

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

通常,您根本不使用begin / end

代码中的错误是在module外部,类名必须是完全限定的。 也就是说,以下将解决问题:

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

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

  • 你需要一个块来执行/ whileuntil @Stefan);
  • 你想rescue一个例外;
  • 你想要一个ensure块。

总结:

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

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

暂无
暂无

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

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