class variables

V

v.nainar

Hello!

What is wrong with the following code? Why is @@id incremented before
and not after the assignment? . ( Sorry if this sounds silly and I have
overlooked something obvious )


#!/usr/local/bin/ruby
class Foo
@@id=1
def initialize(s)
@s=s
@id=setId()
end
def setId()
@id=@@id
@@id+=1
end
end

foo1=Foo.new("one")
foo2=Foo.new("two")
foo3=Foo.new("three")
p foo1,foo2,foo3
Output ->
# <Foo:0xb7d6b4f0 @id=2, @s="one"> # why is @id not 1
# <Foo:0xb7d6b4c8 @id=3, @s="two"> # and 2
# <Foo:0xb7d6b4a0 @id=4, @s="three"> # and 3 ?
 
D

Daniel Tse

v.nainar said:
Hello!

What is wrong with the following code? Why is @@id incremented before
and not after the assignment? . ( Sorry if this sounds silly and I have
overlooked something obvious )


#!/usr/local/bin/ruby
class Foo
@@id=1
def initialize(s)
@s=s
@id=setId()
end
You are assigning to the return value of setId, which is the incremented
@@id: in Ruby, the implicit return value of a function is that of the
last evaluated expression.
 
K

Kevin Brown

Hello!

What is wrong with the following code? Why is @@id incremented before
and not after the assignment? . ( Sorry if this sounds silly and I have
overlooked something obvious )


#!/usr/local/bin/ruby
class Foo
@@id=1
def initialize(s)
@s=s
@id=setId()
end
def setId()
@id=@@id
@@id+=1
end
end

foo1=Foo.new("one")
foo2=Foo.new("two")
foo3=Foo.new("three")
p foo1,foo2,foo3
Output ->
# <Foo:0xb7d6b4f0 @id=2, @s="one"> # why is @id not 1
# <Foo:0xb7d6b4c8 @id=3, @s="two"> # and 2
# <Foo:0xb7d6b4a0 @id=4, @s="three"> # and 3 ?

When somethings at the end of a function, it gets returned implicitly. So,
when you call @id - setId() you're setting @id to the current id (1), then
incrementing, and then then function returns the incremented value,
overwriting your 1 with a 2. Throw a return @s at the end and you'll get the
behaviour you're looking for.
 
V

v.nainar

When somethings at the end of a function, it gets returned implicitly. So,
when you call @id - setId() you're setting @id to the current id (1), then
incrementing, and then then function returns the incremented value,
overwriting your 1 with a 2. Throw a return @s at the end and you'll get the
behaviour you're looking for.
Well it **was** silly of me .Thanks for the quick replies
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top