简体   繁体   中英

Ruby - class variables being overwritten on successive reads

I have a class like so:

class MyNumber
  @@number = nil

  unless @@number
    @@number = rand(10)
  end

  def number
    @@number
  end
end

When I subsequently call the number method on this class the number keeps changing. I just want to set this number once and have it remain the same for the entire life of the class. How can I achieve this.

In java parlance, I am trying to have a static variable and static method for this class.

它应该可以工作,但是您如何调用该类-如果重新加载该类,它将具有不同的值。

It was being caused by rails auto unloading/reloading. There is a workaround that lets the class persist across requests.

In my environment.rb I had to add this

config.after_initialize do
  require 'my_number'
end

I think this could be better written like this:

class MyNumber
  def number
    @@number ||= rand(10)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM