【问题标题】:FIFO Ruby Queues algorithm not workingFIFO Ruby 队列算法不起作用
【发布时间】:2016-08-02 21:02:31
【问题描述】:

构建 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

【问题讨论】:

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


    【解决方案1】:

    在循环遍历数组的同时移动数组是个坏主意。

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

    【讨论】:

    • 运行代码时出现以下错误。 ``` 失败/错误:now_serving(other_deli) #> 收到 :puts 预期的意外参数:(“当前正在服务 Logan。”)得到:(“当前正在服务 Avi。”)-@chumakoff 跨度>
    • katz_deliother_deli 是什么?这些是哪里来的?
    • 这些是来自 Rspec 的一些测试。 @chumakoff
    • Rspec 文件用于测试来自在线教育资源的代码。 github.com/learn-co-curriculum/deli-counter此链接显示了要遵循的说明。@chumakoff
    • 抱歉,没空
    【解决方案2】:

    所以这修复了我的错误

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2017-04-12
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多