[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Why eval is not failing in the third case ( c3

Raj Singh

1/18/2009 9:36:00 PM

>> c1 = 'hello'
>> eval c1
NameError: undefined local variable or method `hello' for main:Object

>> c2 = 'hello #{hi}'
=> "hello \#{hi}"
>> eval c2
NameError: undefined local variable or method `hello' for main:Object

>> c3 = '#{hi} hello'
=> "\#{hi} hello"
>> eval c3
=> nil


My question is why the eval of c3 is returning nil. It should fail
saying that undefined local variable just as it did in the case of c2 ?
--
Posted via http://www.ruby-....

2 Answers

Time World

1/18/2009 9:57:00 PM

0

[Note: parts of this message were removed to make it a legal post.]

2009/1/18 Raj Singh <neeraj.jsr@gmail.com>

> >> c1 = 'hello'
> >> eval c1
> NameError: undefined local variable or method `hello' for main:Object
>
> >> c2 = 'hello #{hi}'
> => "hello \#{hi}"
> >> eval c2
> NameError: undefined local variable or method `hello' for main:Object
>
> >> c3 = '#{hi} hello'
> => "\#{hi} hello"
> >> eval c3
> => nil
>
>
> My question is why the eval of c3 is returning nil. It should fail
> saying that undefined local variable just as it did in the case of c2 ?


It's evaluated as a comment:
#hi hello
If you want #{hi} to be replaced by the content of the variable hi, you
should use double quotes:
c4 = "#{hi} hello"

Ken Bloom

1/19/2009 12:32:00 AM

0

On Sun, 18 Jan 2009 16:35:31 -0500, Raj Singh wrote:

>>> c1 = 'hello'
>>> eval c1
> NameError: undefined local variable or method `hello' for main:Object
>
>>> c2 = 'hello #{hi}'
> => "hello \#{hi}"
>>> eval c2
> NameError: undefined local variable or method `hello' for main:Object
>
>>> c3 = '#{hi} hello'
> => "\#{hi} hello"
>>> eval c3
> => nil
>
>
> My question is why the eval of c3 is returning nil. It should fail
> saying that undefined local variable just as it did in the case of c2 ?

In the second and third cases, everything after (and including) the # is
interpreted as a comment. Thus, you're executing

hello
hello #{hi}
#{hi} hello

In case 1, hello is a undefined method, so a NameError is raised
In case 2, hello comes before the comment, so it gets executed (with no
arguments). A NameError is raised because it's an undefined method.
In case 3, hello is part of the comment. Nothing gets executed, so no
NameError is raised.



--
Chanoch (Ken) Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu...