Instance variables on anonymous objects does not work?

L

LAMBEAU Bernard

Could someone explain why the following code does not work?

... and sorry because I guess it's something stupid that I didn't catch in Ruby.

a = Object.new.instance_eval do
@names = ["you", "me"]
end
def a.say_hello
puts "Hello: " << @names.inspect
end
a.say_hello

the code prints Hello: nil

thx
blambeau
 
L

LAMBEAU Bernard

Much more strange: why does this one work?? Same behavior on both ruby
1.8.7 and ruby 1.9

a = Object.new
a.instance_eval do
@names = ["you", "me"]
end
def a.say_hello
puts "Hello: " << @names.inspect
end
a.say_hello

the code prints Hello: ["you", "me"]
 
L

LAMBEAU Bernard

OK, something that I didn't catch of course.

a = ... invocation is wrong.

Sorry for the stupid question.
blambeau
 
Z

Zayd Connor

LAMBEAU said:
OK, something that I didn't catch of course.

a = ... invocation is wrong.

Sorry for the stupid question.
blambeau

How is the a =... invocation wrong? Just coming from a curious ruby
beginner
 
L

lasitha

How is the a =... invocation wrong? Just coming from a curious ruby
beginner

Compare the value of a in both cases (in irb):

01> a = Object.new
--> #<Object:0x732e7c>
02> a.instance_eval do
03> @names = ["you", "me"]
04> end
--> ["you", "me"]
05> a
--> #<Object:0x732e7c @names=["you", "me"]>

06> a = Object.new.instance_eval do
07> @names = ["you", "me"]
08> end
--> ["you", "me"]
09> a
--> ["you", "me"]

Does that help?
lasitha
 

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

Forum statistics

Threads
474,177
Messages
2,570,954
Members
47,507
Latest member
codeguru31

Latest Threads

Top