假设我们在一家超市里,每次有人进入时,他们都会排队等候排队。我需要:
这是我的代码:
def take_a_number(array)
counter = 0
counter += 1
array << counter
counter
end
每次我调用此方法时,它将使计数器降至零。我该如何避免这种情况,并保留总人数?
答案 0 :(得分:0)
您应该在方法定义之外将counter声明为0
答案 1 :(得分:0)
最好将其存储在类的实例变量中。但是没有更多上下文,但是基本上您已经将信息包含在数组中,您应该查看最后一个计数器的设置:
def take_a_number(array)
if array.empty?
counter = 1
else
counter = array.last + 1
end
array << counter
counter
end
您可以将此语句简化为:
def take_a_number(array)
counter = array.empty? ? 1 : array.last + 1
array << counter
counter
end
另一种方法是仅查看数组的长度:
def take_a_number(array)
counter = array.length + 1
array << counter
counter
end
或者您甚至可以写得更短:
def take_a_number(array)
array << array.length+1
array.length
end
但是正如我刚开始所说的那样,最好将所有这些打包到一个模型中,然后可以使用实例变量
class Queue
def initialize
@list = []
@current_number = 0
end
def take_a_number
@current_number += 1
@list << @current_number
@current_number
end
def take_turn
@list.shift
end
end
waiting_line_1 = Queue.new #get a new queue, you could have multiple ones...
waiting_line_1.take_a_number #first person takes a number
waiting_line_1.take_a_number #second person takes a number
waiting_line_1.take_turn #first person takes a turn / is called