From: Kevin Brown Date: 2005-09-28T15:52:54+09:00 Subject: Re: class variables On Wednesday 28 September 2005 00:03, v.nainar wrote: > 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 -> > # # why is @id not 1 > # # and 2 > # # 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.