-2

我是红宝石新手。我创建了一个名为 Station 的类,如下所示:

class Station

  def initialize()
    @no_crates = 5
    while(true)
      sleep(1)
      @no_crates = Integer(@no_crates) + 1
    end
  end

  def get_no_crates()
    return @no_crates
  end
end

变量@no_crates 应该随着时间的推移而增加,所以我想在单独的线程中运行这些类。我怎样才能做到这一点,然后不时调用 get_no_crates() 函数来获取@no_crates?

我尝试了以下但ofcouse它不工作

st =  Thread.new{ Station.new()}
while(true)
  sleep(1)
  puts st.get_no_crates()
end
4

1 回答 1

3

看到这个,试着理解你做错了什么。

class Station

  def initialize()
    @no_crates = 5
  end

  def run
    while(true)
      sleep(1)
      @no_crates = Integer(@no_crates) + 1
    end
  end

  def get_no_crates()
    return @no_crates
  end
end


station = Station.new
st =  Thread.new{ station.run }
while(true)
  sleep(1)
  puts station.get_no_crates()
end

这是一个更好看的版本

class Station

  attr_reader :no_crates

  def initialize
    @no_crates = 5
  end

  def run
    loop do
      sleep 1
      @no_crates = @no_crates + 1
    end
  end
end

station = Station.new
st =  Thread.new{ station.run }
loop do
  sleep 1 
  puts station.no_crates
end
于 2012-12-21T05:10:40.327 回答