diff --git a/ruby/lib/lox/environment.rb b/ruby/lib/lox/environment.rb new file mode 100644 index 0000000..3f32be2 --- /dev/null +++ b/ruby/lib/lox/environment.rb @@ -0,0 +1,17 @@ +module Lox + class Environment + def initialize + @values = {} + end + + def define(name, value) + @values[name] = value + end + + def get(token) + name = token.lexeme + + @values.fetch(name) { raise RuntimeError.new(token, "Undefined variable '#{name}'.") } + end + end +end diff --git a/ruby/test/lox/test_environment.rb b/ruby/test/lox/test_environment.rb new file mode 100644 index 0000000..8079a17 --- /dev/null +++ b/ruby/test/lox/test_environment.rb @@ -0,0 +1,23 @@ +require_relative "../test_helper" + +require "lox/environment" +require "lox/error" +require "lox/token" + +class TestEnvironment < Lox::Test + def setup + @env = Lox::Environment.new + end + + def test_define + @env.define("name", "value") + + assert_equal "value", @env.get(Lox::Token.new(:IDENTIFIER, "name", "name", 0)) + end + + def test_get + assert_raises Lox::RuntimeError, "Undefined variable name 'name'." do + @env.get(Lox::Token.new(:IDENTIFIER, "name", "name", 0)) + end + end +end