我对红宝石很陌生。我试图在文本文件中搜索单词的任何实例(而不是问题)。然后,当这个单词被发现时,它会显示周围的文本(可能是目标单词前后的3-4个单词,而不是整行),输出到一个实例列表并继续搜索。
示例:
飞快的棕色狐狸跳过那只懒狗。
搜索词:跳转
输出:...brown fox跳过.
任何帮助都是非常感谢的。
def word_exists_in_file
f = File.open("test.txt")
f.each do line
print line
if line.match /someword/
return true
end
end
false
end发布于 2010-04-19 18:16:18
def find_word(string, word)
r1 = /\w+\W/
r2 = /\W\w+/
"..." + string.scan(/(#{r1}{0,2}#{word}#{r2}{0,2})/i).join("...") + "..."
end
string = "The quick brown fox jumped over the lazy dog."
find_word(string, "the")
#=> "...The quick brown...jumped over the lazy dog..."
find_word(string, "over")
#=> "...fox jumped over the lazy..."这不是完美的解决方案,只是一条路,所以要绕开它。
发布于 2010-04-20 08:40:49
Rails有一个名为excerpt的文本助手,它正是这样做的,所以如果您想在Rails视图中这样做:
excerpt('The quick brown fox jumped over the lazy dog',
'jumped', :radius => 10)
=> "...brown fox jumped over the..."如果您想使用这个外部Rails (但是安装了Rails宝石),可以加载ActionView:
require "action_view"
ActionView::Base.new.excerpt('The quick brown fox jumped over the lazy dog',
'jumped', :radius => 10)
=> "...brown fox jumped over the..."https://stackoverflow.com/questions/2669580
复制相似问题