Weird behaviour

Hello

Ruby complains when it tries to parse:

"" + "".to_s +""

but the following are correct:

"" + "".to_s + ""
"" + "" +""

Is it because there is no +@ operator defined for the String class ?
If so, why the latter is parsed silently ?

Marcin Mielzynski

Is it because there is no +@ operator defined for the String class ?

no, this is this case

svg% ruby -e '"".to_s +""'
-e:1: undefined method `+@' for "":String (NoMethodError)
svg%

If so, why the latter is parsed silently ?

because with '"" + "".to_s +""' ruby has seen an identifier and it don't
expect +"" at this step

Guy Decoux

"ts" <decoux@moulon.inra.fr> schrieb im Newsbeitrag
news:200407091428.i69ESQl07744@moulon.inra.fr...

> Is it because there is no +@ operator defined for the String class ?

no, this is this case

svg% ruby -e '"".to_s +""'
-e:1: undefined method `+@' for "":String (NoMethodError)
svg%

> If so, why the latter is parsed silently ?

because with '"" + "".to_s +""' ruby has seen an identifier and it

don't

expect +"" at this step

Maybe Ruby tries to parse +"" as unary plus (i.e. number sign) and then
fails on the "" part.

    robert

Maybe Ruby tries to parse +"" as unary plus (i.e. number sign) and then
fails on the "" part.

run it with -w

Guy Decoux

"ts" <decoux@moulon.inra.fr> schrieb im Newsbeitrag
news:200407091512.i69FCFJ09170@moulon.inra.fr...

> Maybe Ruby tries to parse +"" as unary plus (i.e. number sign) and

then

> fails on the "" part.

run it with -w

Good point. I guess "-e:1: undefined method `+@' for "":String
(NoMethodError)" means that the unary plus is not defined for String.
Correct?

Regards

    robert

Good point. I guess "-e:1: undefined method `+@' for "":String
(NoMethodError)" means that the unary plus is not defined for String.
Correct?

yes,

Guy Decoux

So
  "".to_s +""
means
  "".to_s(+"")

and adding parens like so:
  "".to_s() +""
would correct the problem.

So
  "".to_s +""
means
  "".to_s(+"")

it's a little more complex :slight_smile:

   "".to_s +""

is interpreted as

   "".to_s(+"") # unary plus

  and

   "".to_s+""

  is interpreted as

   "".to_s + "" # addition

*but*

   "" + "".to_s +""

is interpreted as

   ("" + "".to_s) +""

this is why ruby give an error, it has an unary plus which don't give a
valid expression

and adding parens like so:
  "".to_s() +""
would correct the problem.

yes, because with

  "" + "".to_s() +""

it's interpreted as

  ("" + "".to_s()) + ""

the second `+' is seen as the addition not the unary plus

like in this case :slight_smile:

   "" + "".to_s+""

Guy Decoux