I fi开发者_StackOverflow中文版nd myself wondering if there's a built-in Ruby method to get the nth number in a 12-element sequence, no matter how large 'n' is.
For example, if I have a sequence (portrayed as an array below) that has 3 elements, and if I try to access the fourth element, it starts from the beginning. Here's a method that will do this, but I wonder if there's a built-in way to do it.
Array.class_eval do
def sequenced(n)
n/size >= 1 ? fetch(n%size) : fetch(n)
end
end
['a', 'b', 'c'].sequenced(3) => 'a'
Why do you need to special case the n < size case? Just use fetch(n%size)
In Ruby 1.9:
['a', 'b', 'c'].cycle.take(size).last
精彩评论