Hi,
In [ruby-talk :15237 ] the message: "[ruby-talk:15237] RE: Bug or
feature? eval("x=5") ", on May/16 13:38(JST) "Joseph McDonald" writes:
>> eval("x=5")
>> puts x # Never heard of x!
>weirdness. It works in irb but not as a script:
>
>irb(main):001:0> eval("x=5")
>5
>irb(main):002:0> puts x
>5
>nil
>irb(main):003:0>
This is a difference of execution semantics of Ruby and irb.
See the following document in detail:
## ---
= Restrictions
Because irb evaluates the inputs immediately after the imput is
syntactically completed, irb gives slight different result than
directly use ruby. Known difference is pointed out here.
== Declaration of the local variable
The following causes an error in ruby:
eval "foo = 0"
foo
--
-:2: undefined local variable or method `foo' for #<Object:0x40283118> (NameError)
---
NameError
Though, the above will successfully done by irb.
>> eval "foo = 0"
=> 0
>> foo
=> 0
Ruby evaluates a code after reading entire of code and determination
of the scope of local variables. On the other hand, irb do
immediately. More precisely, irb evaluate at first
evel "foo = 0"
then foo is defined on this timing. It is because of this
incompatibility.
If you'd like to detect those differences, begin...end can be used:
>> begin
?> eval "foo = 0"
>> foo
>> end
NameError: undefined local variable or method `foo' for #<Object:0x4013d0f0>
(irb):3
(irb_local_binding):1:in `eval'
-- keiju