[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Instance variables on anonymous objects does not work?

LAMBEAU Bernard

2/13/2009 11:00:00 AM

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

4 Answers

LAMBEAU Bernard

2/13/2009 11:03:00 AM

0

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"]

LAMBEAU Bernard

2/13/2009 11:07:00 AM

0

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

a = ... invocation is wrong.

Sorry for the stupid question.
blambeau


On Fri, Feb 13, 2009 at 12:02 PM, LAMBEAU Bernard <blambeau@gmail.com> wrote:
> 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"]
>
>

Zayd Abdullah

2/23/2009 4:37:00 AM

0

LAMBEAU Bernard wrote:
> 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
--
Posted via http://www.ruby-....

lasitha

2/23/2009 5:05:00 AM

0

On Mon, Feb 23, 2009 at 10:06 AM, Zayd Connor <devrubygem@gmail.com> wrote:
> 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