开发者

How to change a Ruby Class Variable value

开发者 https://www.devze.com 2023-03-23 01:57 出处:网络
I\'m new to Ruby and I what I want to do开发者_JAVA百科 is the following class WS< ActiveRecord::Base

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:

How to change a Ruby Class Variable value

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号