Ruby 开始和结束块使用



我已经编写了找到"瓶子问题"的逻辑

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

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

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

错误"><主>":未初始化的常量操作(名称错误(

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

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

通常您根本不使用begin/end

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

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

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

  • 您需要在while/until内执行一个区块(归功于 @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]

最新更新