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 ?
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 ?