gpt4 book ai didi

ruby - 如何延迟 Ruby 中的循环?

转载 作者:数据小太阳 更新时间:2023-10-29 06:40:05 30 4
gpt4 key购买 nike

例如,如果我想制作一个计时器,我该如何在循环中进行延迟以使其以秒为单位计数,而不只是以毫秒为单位循环?

最佳答案

鉴于您提出的非常简单直接的问题,上面的“评论”是您的答案:

1.upto(5) do |n|
puts n
sleep 1 # second
end

您可能希望定期运行某个方法,而不阻塞其余代码。在这种情况下,您想使用一个线程(并可能创建一个互斥量以确保两段代码不会同时尝试修改同一数据结构):

require 'thread'

items = []
one_at_a_time = Mutex.new

# Show the values every 5 seconds
Thread.new do
loop do
one_at_a_time.synchronize do
puts "Items are now: #{items.inspect}"
sleep 5
end
end
end

1000.times do
one_at_a_time.synchronize do
new_items = fetch_items_from_web
a.concat( new_items )
end
end

关于ruby - 如何延迟 Ruby 中的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28240510/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com