Eval Weird Behavior

Hi all… I’m doing some Genetic Programming for my AI class, and I ran
into a weird “bug” or behavior with the “eval()” function.

Mainly what I do is build a three of evaluable nodes, and then pour the
structure into a string, which I escape in order to make it “evaluable”.

So after a run, a possible program would look like:


  • whileInCorridorRange will check for a ceratain condition, and while
    it is true it will call eval for the rest of the string “do2…” same
    would be for do2 which would call turnRight() and then turnRight()…
    turnRight() itself is a terminal so it won’t call anyone else.

This works pretty good and causes no problem… but if I go deeper into

I will get:

SyntaxError: (eval):1:in do': compile error (eval):1: syntax error, unexpected tIDENTIFIER, expecting ')' whileInCorridorRange("ifConvexCorner(\"turnRight()\", \"do2(\\"whileTooFarFromWall(\\\"turnRight()\\\")\\",\\"whileInCorridorRange(\\\"turnLeft()\\\")\\")\")") ^ (eval):1: syntax error, unexpected ',', expecting $end whileInCorridorRange("ifConvexCorner(\"turnRight()\", \"do2(\\"whileTooFarFromWall(\\\"turnRight()\\\")\\",\\"whileInCorridorRange(\\\"turnLeft()\\\")\\")\")") ^ from ./robot.rb:107:indo’
from ./geneticProgram.rb:128:in eval' from ./robot.rb:107:indo’
from ./geneticProgram.rb:128:in `evaluate’
from (irb):34

It looks like, using five slashes \\" to escape the quotes cause the
eval function to break.

I’m not sure if this is a bug or has some “meant to be” explanation, but
I’d really appreciate any pointers.


Ok I’m answering my own question, just in case anyone stumbles across
this issue and ends in my post:

I thought you had to add a pair of slashes (\) to escape the quotes(")
but it seems that you have to add twice the last number of slashes plus

So if you had something like this:

class Test
def a(arg)
def b
puts “b”

In order to recursively call function a and pass “b” to the las call in
order to get a printed b… you’d have to:

1 Call:
–One Slash
2 Calls:
–Three Slashes ( 1 * 2 + 1)

3 Calls:
–Seven Slashes ( 3 * 2 + 1)

4 Calls:
–Fifteen Slashes (7*2 +1 )

I’m not sure if this is useful for anyone besides me and my pretty
small-scoped project, but who would know?

Thanks again

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs