creating variable with eval

G

Geert Fannes

------_=_NextPart_001_01C56514.8445A09C
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

Hello, what is the scope of a variable created inside an eval()
statement? To demonstrate what I mean, I created the following program:

=20

a=3D1

puts local_variables.sort.collect{|v|"1 #{v}: #{eval(v)}"}

eval("b=3D2")

puts local_variables.sort.collect{|v|"2 #{v}: #{eval(v)}"}

c=3Deval("b")

d=3Db

puts local_variables.sort.collect{|v|"3 #{v}: #{eval(v)}"}

=20

This gives as output:

=20

1 a: 1

1 c:

1 d:

2 a: 1

2 b: 2

2 c:

2 d:

tmp.rb:6: undefined local variable or method `b' for main:Object
(NameError)

=20

Apparently, Ruby creates immediately the variables a,c,d (so all the
variables that are on the left-hand-side of an assignment), even before
he actually processed the assignment.

After processing the line "eval("b=3D2")", Ruby also created the local
variable b, which is accessible via eval("b"), but not directly (Ruby
crashes on line 6, "d=3Db" because he does not know local variable b,
which is clearly NOT the case, since he did write out local variable b
correctly).

=20

Any idea how these things work in Ruby and why my above program does
not?

=20

If you are wondering why I need this: I want to develop a
"named-argument" system for ruby-methods. My plan is to pass in a hash
all the optional arguments and automatically create variables for all
the keys in this hash. This generic procedure to create variables from
the hash-keys, does not know the names for these variables, but the rest
of the method that uses the named arguments does:

=20

def
some_method(required_arg1,required_arg2,opt_arg_hash=3D{:eek:pt_arg1=3D>nil,=
:eek:p
t_arg2=3D>nil})

#this generic method should create the variables opt_arg1 and opt_arg2

process_opt_args(opt_arg_hash)

=20

#here we should be able to use the variables opt_arg1 and opt_arg2
directly, without having

#to write opt_arg_hash[:eek:pt_arg1] and opt_arg_hash[:eek:pt_arg2]

puts(opt_arg1)

puts(opt_arg2)

end

=20

Greetings,

Geert.


------_=_NextPart_001_01C56514.8445A09C--
 
R

Robert Klemme

This comes up again and again. You might want to search the archives.

Short story: Ruby determines local variables at parse time. Although you
can bind values to local vars with eval you cannot access them outside of
eval because they are not known there:

14:44:40 [source]: ruby -e 'eval("x=10");p(eval("x"))'
10
14:44:46 [source]: ruby -e 'eval("x=10");p x'
-e:1: undefined local variable or method `x' for main:Object (NameError)
14:44:51 [source]: ruby -e 'x=nil;p x;eval("x=10");p x'
nil
10

Apart from that: your dynamic created variables will be of no use as the
method body cannot access them. The simplest solutions:

1) Access the hash instead of using local vars

2) Generate the complete method code

In any case: make sure you have default values so you can init variables
not defined in the hash. Otherwise you'll see the same error:

14:48:05 [source]: ruby -e 'def x(a) b + a end;x 10'
-e:1:in `x': undefined local variable or method `b' for main:Object
(NameError)
from -e:1

Kind regards

robert
 
S

Stefan Kaes

Robert said:
This comes up again and again. You might want to search the archives.
This comes up again and again because the current behaviour is
inconsistent with the proudly stated principle of least suprise. As I
have said before: eval "code" should be equivalent to code in all contexts.
Short story: Ruby determines local variables at parse time. Although you
can bind values to local vars with eval you cannot access them outside of
eval because they are not known there:

14:44:40 [source]: ruby -e 'eval("x=10");p(eval("x"))'
10
14:44:46 [source]: ruby -e 'eval("x=10");p x'
-e:1: undefined local variable or method `x' for main:Object (NameError)
14:44:51 [source]: ruby -e 'x=nil;p x;eval("x=10");p x'
nil
10
However,

$ irb
irb(main):001:0> eval "x=10"; p x
NameError: undefined local variable or method `x' for main:Object
from (irb):1
irb(main):002:0> eval "x=10"
=> 10
irb(main):003:0> p x
10
=> nil
irb(main):004:0> exit

If this isn't bound to be confusing ...

Regards,

Stefan
 
R

Robert Klemme

Stefan said:
Robert said:
This comes up again and again. You might want to search the
archives.
This comes up again and again because the current behaviour is
inconsistent with the proudly stated principle of least suprise. As I
have said before: eval "code" should be equivalent to code in all
contexts.
Short story: Ruby determines local variables at parse time.
Although you can bind values to local vars with eval you cannot
access them outside of eval because they are not known there:

14:44:40 [source]: ruby -e 'eval("x=10");p(eval("x"))'
10
14:44:46 [source]: ruby -e 'eval("x=10");p x'
-e:1: undefined local variable or method `x' for main:Object
(NameError) 14:44:51 [source]: ruby -e 'x=nil;p x;eval("x=10");p x'
nil
10
However,

$ irb
irb(main):001:0> eval "x=10"; p x
NameError: undefined local variable or method `x' for main:Object
from (irb):1
irb(main):002:0> eval "x=10"
=> 10
irb(main):003:0> p x
10
=> nil
irb(main):004:0> exit

If this isn't bound to be confusing ...

You cannot trust IRB on local variables. This too comes up from time to
time in these circumstances... :)

Regards

robert
 
G

Gavin Kistner

This comes up again and again because the current behaviour is
inconsistent with the proudly stated principle of least suprise.

Matz has stated repeatedly that the POLS is *not* supposed to be
applied to everyone. It is obviously impossible to provide little-or-
no surprise to everyone, given that people have different expectations.

IIRC, Matz has asked that people stop using it. (Or at least
certainly do not attribute it to him.) It was (again, IIRC) merely a
general design guideline which Matz applied to his own expectations
when designing certain features of the language.

How often have you seen people (myself as a newbie included) shout
"WTF, this isn't at all what I expected. So much for POLS!" when
things turn out imperfectly?

I have seen various powerpoint slides that tout Ruby's POLS as a
feature; I personally find them to smell overly of hype, and (to the
degree that I believe such overreaching claims will turn off
newcomers who can sense marketese) would suggest that we heavily tone
down any invocations of the POLS.
 
A

Ara.T.Howard

Matz has stated repeatedly that the POLS is *not* supposed to be applied to
everyone. It is obviously impossible to provide little-or-no surprise to
everyone, given that people have different expectations.

IIRC, Matz has asked that people stop using it. (Or at least certainly do
not attribute it to him.) It was (again, IIRC) merely a general design
guideline which Matz applied to his own expectations when designing certain
features of the language.

How often have you seen people (myself as a newbie included) shout "WTF,
this isn't at all what I expected. So much for POLS!" when things turn out
imperfectly?

I have seen various powerpoint slides that tout Ruby's POLS as a feature; I
personally find them to smell overly of hype, and (to the degree that I
believe such overreaching claims will turn off newcomers who can sense
marketese) would suggest that we heavily tone down any invocations of the
POLS.

i can see your point - but this really shouldn't be any issue with computer
programmers since a moment of reflection of the 'specification' reveals that
it's POLS and not PONS.

2 cts.

-a
--
===============================================================================
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| My religion is very simple. My religion is kindness.
| --Tenzin Gyatso
===============================================================================
 
J

James Britt

Gavin said:
Matz has stated repeatedly that the POLS is *not* supposed to be
applied to everyone. It is obviously impossible to provide little-or- no
surprise to everyone, given that people have different expectations.

Really. I'm surprised people still keep bringing up POLS.



James

--

http://www.ruby-doc.org - The Ruby Documentation Site
http://www.rubyxml.com - News, Articles, and Listings for Ruby & XML
http://www.rubystuff.com - The Ruby Store for Ruby Stuff
http://www.jamesbritt.com - Playing with Better Toys
 
J

James Britt

Gavin Kistner wrote:
...
I have seen various powerpoint slides that tout Ruby's POLS as a
feature; I personally find them to smell overly of hype, and (to the
degree that I believe such overreaching claims will turn off newcomers
who can sense marketese) would suggest that we heavily tone down any
invocations of the POLS.

Yes, and in general the hype that tends to bite back are the assertions
that are largely subjective or otherwise unverifiable.

Claims of faster development, greater productivity, least surprise, most
natural syntax, and such, are next to impossible to objectively
quantify, so someone looking to knock Ruby, or anyone who is reasonably
skeptical, will find it easy to toss back counter-claims and disappointment.

However true these claims may be for most (if not all) of the people
reading ruby-talk, they are not things you can simply push on people new
to Ruby. Folks need to discover (or not, as the case may be) them
through personal experience.


James
 
S

Stefan Kaes

Robert said:
You cannot trust IRB on local variables. This too comes up from time to
time in these circumstances... :)
Which means that irb has a bug that doesn't get fixed.

-- stefan
 
A

Alexandru Popescu

#: on behalf of James Britt :: 5/30/2005 6:42 PM :#
Gavin Kistner wrote:
...


Yes, and in general the hype that tends to bite back are the assertions
that are largely subjective or otherwise unverifiable.

Claims of faster development, greater productivity, least surprise, most
natural syntax, and such, are next to impossible to objectively
quantify, so someone looking to knock Ruby, or anyone who is reasonably
skeptical, will find it easy to toss back counter-claims and disappointment.

If all these can be used in both directions why keep using them?

:alex |.::the_mindstorm::.|
 
R

Robert Klemme

Stefan said:
Which means that irb has a bug that doesn't get fixed.

No, it's not a bug. It's a conceptual thing that cannot be fixed: IRB
must process Ruby code line by line while normally all the code in a file
gets parsed and compiled into bytecode and then executed.

Kind regards

robert
 
R

Robert Klemme

Gavin said:
Matz has stated repeatedly that the POLS is *not* supposed to be
applied to everyone. It is obviously impossible to provide little-or-
no surprise to everyone, given that people have different
expectations.

Another point about surprises: when considering information theory suprise
is an important thing and only surprises make us learn something.
Consider a channel that transfers only 1's. You cannot derive any
information from the next 1 you receive (entropy = 0). If the channel
spits out 0's and 1's you have higher entropy and higher information
content. The entropy is related to the level of surprise you experience
when you receive a symbol.

http://en.wikipedia.org/wiki/Information_entropy

In short: surprise isn't bad alltogether.

Kind regards

robert
 
S

Stefan Kaes

Robert said:
Stefan Kaes wrote:



No, it's not a bug. It's a conceptual thing that cannot be fixed: IRB
must process Ruby code line by line while normally all the code in a file
gets parsed and compiled into bytecode and then executed.
Bytecode? Whishful thinking , I suppose.

Anyway, entering code line by line to irb should give the same effect as
running the same code from a file. I don't know any interpreted language
that would give different results for the interactive shell than running
the whole thing from a file.

-- stefan
 

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
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top