Skip to content

Instantly share code, notes, and snippets.

@temirov
Last active November 23, 2015 17:45
Show Gist options
  • Save temirov/bdb9e72c8a5b890eeb37 to your computer and use it in GitHub Desktop.
Save temirov/bdb9e72c8a5b890eeb37 to your computer and use it in GitHub Desktop.
A class that implements cyclic array in Ruby
class CyclicArray
include Enumerable
attr_reader :a
def initialize(a = [])
raise ArgumentError unless a.respond_to? :each
@a = a
end
def [](n)
chunks = (n.abs / a.length).next
a.cycle(chunks).to_a[n]
end
private
def method_missing(name, *args, &block)
case
when a.cycle.respond_to?(name)
a.cycle.send(name, *args, &block)
when a.respond_to?(name)
a.send(name, *args, &block)
else
super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment