我已经编写了查找“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/