Shan_Boy
Shan_Boy

Reputation: 19

Ruby Begin and End Block usage

I have written the logic to find the "Bottle's Problem"

  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

I was asked to use Begin and End block outside the module, since its not correct way to use. By doing so I got the following error

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)

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

Upvotes: 1

Views: 245

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

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

Typically you don’t use begin/end at all.

The error in your code is that outside of the module, the class name must be fully qualified. That said, the following will fix the issue:

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

begin/end might be needed when:

  • you need a block to be executed within while / until (credits to @Stefan);
  • you want to rescue an exception;
  • you want to have an ensure block.

The summing up:

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

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

Upvotes: 3

Related Questions