Capturing repeated expressions

36 views
Skip to first unread message

Matthew Sainsbury

unread,
Mar 25, 2015, 5:38:07 PM3/25/15
to treet...@googlegroups.com
I've got a simple grammar like so:

grammar Test
  rule array
    '[' letter (',' letter)* ']'
    {
      def eval
        #???
      end
    }
  end

  rule letter
    [a-zA-Z] 1..1
    {
      def eval
        text_value
      end
    }
  end
end


A sample string in the grammar is "[a,b,c,d]"

I would like the eval method on the array rule to return an array of strings ["a", "b", "c", "d"], but I'm not sure how to do that. I can get the first element by doing:

def eval
  [letter.eval]
end


which would return ["a"]. How do I capture the following letter instances in the expression?

Clifford Heath

unread,
Mar 25, 2015, 8:47:42 PM3/25/15
to treet...@googlegroups.com
Add a label to your iterated group and append the items to a list containing the head item:

rule array
  '[' letter tail:(',' letter) ']'
  {
    def eval
      [letter.text_value] + tail.map{|e| e.letter.text_value}
    end
  }

You can also do this with inject if you prefer that style.

Clifford Heath

Clifford Heath

unread,
Mar 25, 2015, 8:49:36 PM3/25/15
to treet...@googlegroups.com
Gah, forgot the * on the iterated group. You get the picture though.

Clifford Heath

unread,
Mar 25, 2015, 8:50:50 PM3/25/15
to treet...@googlegroups.com
Also, it's tail.elements.map{...}

Sorry for the noise, folk.
Reply all
Reply to author
Forward
0 new messages