Learn Ruby The Hard Way ex48: My Sad Attempt

UPDATE: BETTER SOLUTION 😀 click here to see it.

Observation: I do not like writing the source code based on the unit test -.-

I tried my best to solve this one…here’s my solution, in case anyone would like to see how others have thought about it. Let me know if any of it is unclear.

class Lexicon

def self.scan(input)
words = input.split
directions = [‘north’,’south’,’east’,’west’,’down’,’up’,’right’,’left’,’back’]
verbs = [‘go’,’stop’,’kill’,’eat’]
nouns = [‘door’,’bear’,’princess’,’cabinet’]
stop_words = [‘the’,’in’,’of’,’from’,’at’,’it’]
word = []
sentence = []
results = Hash.new()

words.each do |word|
directions.each do |direction|
if word == direction
pair = [‘direction’, word]
sentence.push(pair)
results[word] = pair
end
end

verbs.each do |verb|
if word == verb
pair = [‘verb’, word]
sentence.push(pair)
results[word] = pair
end
end

stop_words.each do |stop|
if word == stop
pair = [‘stop’, word]
sentence.push(pair)
results[word] = pair
end
end

nouns.each do |noun|
if word == noun
pair = [‘noun’, word]
sentence.push(pair)
results[word] = pair
end
end

if word.to_i.to_s == word
pair = [‘number’, word.to_i]
sentence.push(pair)
results[word] = pair
end

if results[word] == nil
pair = [‘error’, word]
sentence.push(pair)
results[word] = pair
end
end

return sentence
end
end

Advertisements