FIFO Ruby Queues算法不起作用

时间:2016-08-02 21:02:31

标签: ruby ruby-on-rails-4 rspec

构建now_serving方法,该方法应该调出(即放入)下一个人,然后从前面删除它们。如果没有人排队,它应该召唤(放置)"没有人等待服务!"。当我尝试使用shift方法去掉数组中的第一个元素时。我最终得到了错误的输出。这是Ruby代码:



def now_serving(array)
  while array.length != 0
    array.each do |name|
      puts "Currently serving #{name}."
      array.shift
      end
  end
    puts "There is nobody waiting to be served!"
end




但是array.shift只运行一次,如何让它连续删除数组的第一个元素。以下是Rspec的代码:



describe "#now_serving" do
    context "there are no people in line" do
      it "should say that the line is empty" do
        expect($stdout).to receive(:puts).with("There is nobody waiting to be served!")
        now_serving(katz_deli)
      end
    end

    context "there are people in line" do
      it "should serve the first person in line and remove them from the queue" do
        expect($stdout).to receive(:puts).with("Currently serving Logan.")
        now_serving(other_deli)
        expect(other_deli).to eq(%w(Avi Spencer))
      end
    end
  end

end




2 个答案:

答案 0 :(得分:0)

在循环播放数组的同时移动数组是一个坏主意。

def now_serving(array)
  while name = array.shift
    puts "Currently serving #{name}."
  end

  puts "There is nobody waiting to be served!"
end

答案 1 :(得分:0)

所以这解决了我的错误



def now_serving(array)
  queue = Queue.new
  queue = array
    
    if array.length > 0
    puts "Currently serving #{array[0]}."
    array.shift
    else
    puts "There is nobody waiting to be served!"
    end
end