0

Note that eval evaluates its code in a temporary scope. eval can alter the value of instance variables that already exist. But any new instance variables it defines are local to the invocation of eval and cease to exist when it returns. (It is as if the evaluated code is run in the body of a block—variables local to a block do not exist outside the block.)

-- from "the ruby programming" book , chapter 8.3.1

irb(main):001:0> class Point
irb(main):002:1> def initialize(x,y)
irb(main):003:2> @x,@y=x,y
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> p=Point.new(1,2)
=> #
irb(main):007:0> 
irb(main):008:0* def get_bind
irb(main):009:1> binding
irb(main):010:1> end
=> nil
irb(main):011:0> b=p.get_bind
=> #Binding:0x81915b0
irb(main):012:0> 
irb(main):013:0* eval("@x",b)
=> 1
irb(main):014:0> 
irb(main):015:0* eval("@x=10",b)
=> 10
irb(main):016:0> eval("@x",b)

=> 10
irb(main):017:0> 
irb(main):018:0* eval("@z=2",b)
=> 2
irb(main):019:0> eval("@z",b)

=> 2
irb(main):020:0> p.instance_variables
=> [:@x, :@y, :@z]
irb(main):021:0> 
irb(main):022:0* 
irb(main):023:0* 

the instance variable "@z" does NOT cease , why ?

1 Answer 1

1

I don't have the book at hand, but that must be a typo. What the author describes is true for local variables in Ruby >=1.9.

1.9.3:

irb(main):001:0> eval("a=1")
=> 1
irb(main):002:0> a
NameError: undefined local variable or method `a' for main:Object
    from (irb):2
    from /Users/apple/.rbenv/versions/1.9.3-p385/bin/irb:12:in `<main>'

1.8.7:

>> eval("a=1")
=> 1
>> a
=> 1

Edit: Here's a more recent version of the book and it says "local variables".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.