tags:

views:

88

answers:

2

Hi there,

I find 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'
+3  A: 

Why do you need to special case the n < size case? Just use fetch(n%size)

Isaac Cambron
heh...tremendous point....good enough for me :-). By the way, great gravatar. I can't believed they canceled that show after only a few years.
btelles
Yup.. that's the only acceptable solution, I think :)
Trevoke
Loved that show, watched it after school even when I was way too old to be in the target demographic.
Isaac Cambron
Thanks again, gents (and lady(s) unless all.male?)
btelles
+1  A: 

In Ruby 1.9:

['a', 'b', 'c'].cycle.take(size).last
banister
Nifty idea, thanks!
btelles