def fire_away(questions)
@n = (@n || -1) + 1
@order = [*0...questions.size].shuffle if @n % questions.size == 0
questions[@order.shift]
end
q = ["A?", "B?" , "C?" , "D?"]
fire_away q #=> "D?"
fire_away q #=> "A?"
fire_away q #=> "C?"
fire_away q #=> "B?"
fire_away q #=> "B?"
fire_away q #=> "C?"
fire_away q #=> "A?"
fire_away q #=> "D?"
fire_away q #=> "A?"
fire_away q #=> "C?"
fire_away q #=> "B?"
fire_away q #=> "D?"
You may also need the method
def reset_questions
@n = nil
end
@fl00r suggested the following to avoid the need for instance variables that are visible within the class in which fire_away is defined (and avoid the need for the method reset_questions):
def fire_away(questions)
n = -1
order = nil
Proc.new do
n += 1
order = [*0...questions.size].shuffle if n % questions.size == 0
questions[order.shift]
end
end
iterator = fire_away ["A", "B", "C", "D"]
iterator.call #=> "C"
iterator.call #=> "A"
iterator.call #=> "B"
iterator.call #=> "D"
iterator.call #=> "D"
Another way would be to create a separate class (which is quite close to @fl00r's answer).
class Questions
def initialize(*questions)
@questions = questions
@n = -1
end
def next_question
@n += 1
@order = [*[email protected]].shuffle if @n % @questions.size == 0
@questions[@order.shift]
end
end
q = Questions.new("A?", "B?" , "C?" , "D?")
q.next_question #=> "C?"
q.next_question #=> "A?"
q.next_question #=> "D?"
q.next_question #=> "B?"
q.next_question #=> "B?"
Both of these modifications are clearly superior to my original answer.