Skip to content

Instantly share code, notes, and snippets.

@zkayser
Created May 17, 2017 03:50
Show Gist options
  • Save zkayser/245429b5dfb87829f39f72e9870a3936 to your computer and use it in GitHub Desktop.
Save zkayser/245429b5dfb87829f39f72e9870a3936 to your computer and use it in GitHub Desktop.
class Garden
attr_accessor :first_row, :second_row
attr_reader :names
CHARS_TO_PLANTS = {
"G" => :grass,
"C" => :clover,
"R" => :radishes,
"V" => :violets
}
DEFAULT_STUDENTS = [:alice, :bob, :charlie, :david, :eve, :fred, :ginny, :harriet, :ileana, :joseph, :kincaid, :larry]
def initialize(garden, students = DEFAULT_STUDENTS)
rows = garden.split("\n")
@first_row = rows[0]
@second_row = rows[1]
@names = Garden::StudentFormatter.new(students).format
end
def get_plants(name)
plants_for(name).collect do |letter|
CHARS_TO_PLANTS[letter]
end
end
def plants_for(name)
index = @names.find_index(name)
[@first_row[index * 2], @first_row[index * 2 + 1]].concat([@second_row[index * 2], @second_row[index * 2 + 1]])
end
def method_missing(name, *args, &block)
super unless @names.include?(name)
get_plants(name)
end
end
class Garden::StudentFormatter
attr_accessor :data
def initialize(data)
data_classes = data.collect { |student| student.class }
@data = Hash[data.zip(data_classes)]
end
def format
@data.collect { |name, klass| klass.format_student(name) }.sort
end
end
class String
def self.format_student(student)
student.downcase.to_sym
end
end
class Symbol
def self.format_student(student)
student
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment