【问题标题】:Ruby Begin and End Block usageRuby 开始和结束块的使用
【发布时间】:2018-09-11 05:53:46
【问题描述】:

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

  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

错误`

':未初始化的常量操作(NameError)

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

【问题讨论】:

  • 名称必须完全限定:res = Bottle::Operation.new.
  • 感谢它的工作,但它是使用开始和结束功能的正确方法吗?

标签: ruby


【解决方案1】:

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

通常你根本不使用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]

【讨论】:

  • @mwp 不,确实,谢谢,已修复。我不太记得 ruby​​,应该检查一下文档。
  • 您也可以使用它来将多个语句打包到一个表达式中。例如:x = 2; y = begin puts "x is #{x}"; x end * 3。这通常不是很有用,但将调试语句插入表达式是使用它的一种方法。
  • @Amadan 是的,我几乎要提到它,但恕我直言,应该避免使用 Object#tap: y = 42.tap { |x| puts "The answer is: #{x}" }
  • 与修饰符 while / until 结合使用也很有用,例如begin ... end while condition - 无论条件如何,它都会运行身体至少一次。
  • @Stefan 确实,谢谢,我已经用那个更新了答案。
猜你喜欢
  • 2010-12-05
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 1970-01-01
  • 2022-01-17
  • 2015-11-23
  • 1970-01-01
  • 2019-11-06
相关资源
最近更新 更多