/ Published in: Ruby
Expand |
Embed | Plain Text
# Created December 1, 2010 # Released into the public domain by Josh Atkins # # find_adjacent_words('This is a test', 5, 1, true) #=> This # find_adjacent_words('This is a test', 5, 2, false) #=> a test # find_adjacent_words('This is a test', 5, 2, 3) #=> ['This', 'a test'] def find_adjacent_words(text, position, word_count, left_of_position) if left_of_position == 3 adjacent_words = Array.new adjacent_words.insert(-1, find_adjacent_words(text, position, word_count, true)) adjacent_words.insert(-1, find_adjacent_words(text, position, word_count, false)) return adjacent_words else if position == nil || !position.kind_of?(Integer) || position > text.length position = left_of_position ? text.length : 0 else while text[position] != 32 && position >= 0 && position <= text.length position += left_of_position ? -1 : 1 end end original_position = position text = text.strip current_word_count = left_of_position ? 0 : word_count || nil while (left_of_position && position > 1 && (!word_count || current_word_count < word_count)) || (!left_of_position && position < text.length && (!current_word_count || current_word_count > 0)) position += left_of_position ? -1 : 1 if (left_of_position && !(position > 1 && text[position] == 32 && text[position-1] == 32)) || (!left_of_position && !(position < text.length && text[position] == 32 && text[position+1] == 32)) current_word_count += left_of_position ? 1 : -1 if text[position+(left_of_position ? -1 : 1)] == 32 if current_word_count end end return (left_of_position ? text[(position > 0 ? position - 1 : position)..original_position] : text[original_position..position]).to_s.strip end end
You need to login to post a comment.
