Is there a way to evaluate the order of an array? I want to find an array of records ordered by created_at date and then see if the numbers in that array are in sequence?
For instance:
Model.all.order(&:created_at).select("lesson_number)
[1, 2, 4, 3, 5]
should fail because the numbers are not in sequence
I could execute two finds. One that is ordered by “lesson_number” and one that is ordered by created_at date. Convert them both the a string then compare the two. But, seems like a lot of work if a rails method exists to handle such a thing.
You can combine a couple methods in Ruby to do this pretty efficiently.
each_conswill iterate through your array yielding, in this case, each 2 consecutive items. Because we don’t pass it a block, it returns an enumerator that we can iterate through and get a single resulting value usingreduce(a.k.a.inject).Our block compares
aandbusing<=>which will return -1, 0, or 1 depending on whether the first value is “less-than”, equal, or “greater than”. In this case, we want to make sureais-1.In case you’re not familiar with it, the parenthesis in the block argument are Ruby 1.9+, and they allow the arguments to be splatted in (otherwise we would get a 2-item array in our block).