Posted By

jatkins on 12/02/10


Tagged

words index String text word


Versions (?)

Find words adjacent to a word given by its index in a string


 / Published in: Ruby
 

  1. # Created December 1, 2010
  2. # Released into the public domain by Josh Atkins
  3. #
  4. # find_adjacent_words('This is a test', 5, 1, true) #=> This
  5. # find_adjacent_words('This is a test', 5, 2, false) #=> a test
  6. # find_adjacent_words('This is a test', 5, 2, 3) #=> ['This', 'a test']
  7.  
  8. def find_adjacent_words(text, position, word_count, left_of_position)
  9. if left_of_position == 3
  10. adjacent_words = Array.new
  11. adjacent_words.insert(-1, find_adjacent_words(text, position, word_count, true))
  12. adjacent_words.insert(-1, find_adjacent_words(text, position, word_count, false))
  13. return adjacent_words
  14. else
  15. if position == nil || !position.kind_of?(Integer) || position > text.length
  16. position = left_of_position ? text.length : 0
  17. else
  18. while text[position] != 32 && position >= 0 && position <= text.length
  19. position += left_of_position ? -1 : 1
  20. end
  21. end
  22. original_position = position
  23. text = text.strip
  24. current_word_count = left_of_position ? 0 : word_count || nil
  25. 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))
  26. position += left_of_position ? -1 : 1
  27. 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))
  28. current_word_count += left_of_position ? 1 : -1 if text[position+(left_of_position ? -1 : 1)] == 32 if current_word_count
  29. end
  30. end
  31. return (left_of_position ? text[(position > 0 ? position - 1 : position)..original_position] : text[original_position..position]).to_s.strip
  32. end
  33. end

Report this snippet  

You need to login to post a comment.