How to change a Ruby Class Variable value
I'm new to Ruby and I what I want to do开发者_JAVA百科 is the following
class WS< ActiveRecord::Base
@@SequenceNumber = 0
def self.oper1
@@SequenceNumber = 2
end
def self.oper2
@@SequenceNumber += 1
puts @@SequenceNumber.to_s
end
def self.oper3
puts @@SequenceNumber.to_s
end
end
If I do something like:
WS.oper1
WS.oper2
WS.oper3
I get the following output:
3
2
Why isn't my @@SequenceNumber += 1 working? What am I doing wrong?
Thank you.
Works just fine:
class WS
@@sequence_number = 0
def self.oper1
@@sequence_number = 2
end
def self.oper2
puts @@sequence_number += 1
end
def self.oper3
puts @@sequence_number
end
end
WS.oper3
# 0
WS.oper1
WS.oper2
# 3
WS.oper3
# 3
[Note: I took the liberty of Rubyfying your code a little bit.]
This is working at expected:
精彩评论