weird behaviour

L

lopex

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
 
T

ts

l> 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%

l> 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
 
R

Robert Klemme

ts said:
l> 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%

l> 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
 
T

ts

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

run it with -w


Guy Decoux
 
R

Robert Klemme

ts said:
R> Maybe Ruby tries to parse +"" as unary plus (i.e. number sign) and then
R> 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
 
T

ts

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

yes,


Guy Decoux
 
D

Dave Burt

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

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

ts

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

it's a little more complex :)

"".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

D> and adding parens like so:
D> "".to_s() +""
D> 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 :)

"" + "".to_s+""




Guy Decoux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,148
Messages
2,570,838
Members
47,385
Latest member
Joneswilliam01

Latest Threads

Top