Sha256: 6ca4a9df0b2757fc37ebff6dcd222898131cd70964d7d48976d653c6bf6ad754

Contents?: true

Size: 1.05 KB

Versions: 4

Compression:

Stored size: 1.05 KB

Contents

# frozen_string_literal: true

class Code
  class Node
    class While < Node
      WHILE_KEYWORD = "while"
      UNTIL_KEYWORD = "until"
      LOOP_KEYWORD = "loop"

      def initialize(parsed)
        @operator = parsed.delete(:operator)
        @statement = Statement.new(parsed.delete(:statement)) if parsed[:statement]
        @body = Code.new(parsed.delete(:body))
        super(parsed)
      end

      def evaluate(**args)
        case @operator
        when WHILE_KEYWORD
          last = Object::Nothing.new

          last = @body.evaluate(**args) while @statement.evaluate(
            **args
          ).truthy?

          last
        when UNTIL_KEYWORD
          last = Object::Nothing.new

          last = @body.evaluate(**args) while @statement.evaluate(**args).falsy?

          last
        when LOOP_KEYWORD
          loop { @body.evaluate(**args) }
          raise NotImplementedError
        else
          raise NotImplementedError, @operator
        end
      rescue Error::Break => e
        e.value || Object::Nothing.new
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
code-ruby-0.10.3 lib/code/node/while.rb
code-ruby-0.10.2 lib/code/node/while.rb
code-ruby-0.10.1 lib/code/node/while.rb
code-ruby-0.10.0 lib/code/node/while.rb