From ff0aae8ecec35fee3e1fcf6e9357a01ad2820089 Mon Sep 17 00:00:00 2001 From: Gwenhael Le Moine Date: Tue, 9 Nov 2021 21:58:25 +0100 Subject: [PATCH] pass all tests --- lib/parser.rb | 15 ++++++++++++--- spec/parser_spec.rb | 2 +- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/lib/parser.rb b/lib/parser.rb index 957dd04..7a6a6e5 100644 --- a/lib/parser.rb +++ b/lib/parser.rb @@ -14,10 +14,17 @@ module Rpn splitted_input = input.split(' ') parsed_tree = [] + opened_programs = 0 + closed_programs = 0 + string_delimiters = 0 regrouping = false + splitted_input.each do |elt| parsed_entry = { value: elt } + opened_programs += 1 if elt[0] == '«' + string_delimiters += 1 if elt[0] == '"' + if regrouping parsed_entry = parsed_tree.pop @@ -46,11 +53,10 @@ module Rpn parsed_entry[:value] = "'#{parsed_entry[:value]}'" if parsed_entry[:value][0] != "'" end end - # parsed_entry[:value] = elt[1..] if [:program, :string, :name].include?( parsed_entry[:type] ) end - regrouping = ( (parsed_entry[:type] == :string && elt.size == 1 && elt[-1] != '"') || - (parsed_entry[:type] == :program && elt[-1] != '»') ) + regrouping = ( (parsed_entry[:type] == :string && string_delimiters % 2 != 0) || + (parsed_entry[:type] == :program && opened_programs > closed_programs ) ) if parsed_entry[:type] == :numeric i = parsed_entry[:value].to_i @@ -59,6 +65,9 @@ module Rpn parsed_entry[:value] = i == f ? i : f end + closed_programs += 1 if elt[-1] == '»' + string_delimiters += 1 if elt.length > 1 && elt[-1] == '"' + parsed_tree << parsed_entry end diff --git a/spec/parser_spec.rb b/spec/parser_spec.rb index 54b7026..3d5d0f5 100644 --- a/spec/parser_spec.rb +++ b/spec/parser_spec.rb @@ -13,7 +13,7 @@ class TestParser < Test::Unit::TestCase def test_word result = Rpn::Parser.new.parse_input( 'dup' ) - assert_equal [{ value: 'dup', type: :word }], result + assert_equal [{ value: "'dup'", type: :name }], result end def test_string