Created
April 1, 2020 13:06
-
-
Save sunny/9a9a1a1fc89feff5f9d4f6e4e76bf833 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Snail | |
include Enumerable | |
def initialize(data) | |
@data = data | |
@direction = :right | |
@x = 0 | |
@y = 0 | |
end | |
def each | |
while (value = fetch(@x, @y)) | |
yield value | |
move | |
end | |
end | |
private | |
def fetch(x, y) | |
@data.dig(y, x) if x >= 0 && y >= 0 | |
end | |
def move | |
# Remove value for the following loops | |
@data[@y][@x] = nil | |
@direction = next_direction unless fetch(*next_position) | |
@x, @y = next_position | |
end | |
def next_position | |
case @direction | |
when :right then [@x + 1, @y] | |
when :left then [@x - 1, @y] | |
when :down then [@x, @y + 1] | |
when :up then [@x, @y - 1] | |
end | |
end | |
def next_direction | |
directions = %i[right down left up] | |
directions.fetch(directions.index(@direction) + 1, directions.first) | |
end | |
end | |
snail = Snail.new([ | |
%w[A B C D E F G H], | |
%w[I J K L M N O P], | |
%w[Q R S T U V W X], | |
%w[Y Z 0 1 2 3 4 5], | |
%w[6 7 8 9 10 11 12 13], | |
%w[14 15 16 17 18 19 20 21], | |
]) | |
p snail.to_a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment