红宝石鞋搜索框
问题描述:
我有一个简短的脚本,它使用正则表达式搜索文件中用户输入的特定短语。基本上,它是一个简单的搜索框。红宝石鞋搜索框
我现在试图让这个搜索框有一个图形用户界面,这样用户可以输入一个框,并将他们的匹配“提醒”给他们。
我是使用红宝石鞋的新手,并且在TheShoeBox网站上使用过这些例子。
任何人都可以指出我的错在哪里我的代码?
这里是我的命令行版本的作品:
string = File.read('db.txt')
puts "Enter what you're looking for below"
begin
while(true)
break if string.empty?
print "Search> "; STDOUT.flush; phrase = gets.chop
break if phrase.empty?
names = string.split(/\n/)
matches = names.select { |name| name[/#{phrase}/i] }
puts "\n \n"
puts matches
puts "\n \n"
end
end
这是我试图在使用它红宝石鞋内:
Shoes.app :title => "Search v0.1", :width => 300, :height => 150 do
string = File.read('db.txt')
names = string.split(/\n/)
matches = names.select { |name| name[/#{phrase}/i] }
def search(text)
text.tr! "A-Za-z", "N-ZA-Mn-za-m"
end
@usage = <<USAGE
Search - This will search for the inputted text within the database
USAGE
stack :margin => 10 do
para @usage
@input = edit_box :width => 200
end
flow :margin => 10 do
button('Search') { @output.matches }
end
stack(:margin => 0) { @output = para }
end
非常感谢
答
那么,对于初学者来说,第一个码位可以被整理。
file = File.open 'db.txt', 'rb'
puts "Enter (regex) search term or quit:"
exit 1 unless file.size > 0
loop do
puts
print "query> "
redo if (query = gets.chomp).empty?
exit 0 if query == "quit"
file.each_line do |line|
puts "#{file.lineno}: #{line}" if line =~ /#{query}/i
end
file.rewind
end
的rb
选项允许其按预期在Windows(尤其是鞋子,你应该尝试与平台无关)。 chomp
去掉\r\n
和\n
但不是a
例如,而chop
只是盲目地取走最后一个字符。 loop do end
比while true
更好。另外为什么在一个变量存储匹配?只是通过线(它允许CRLF结尾)文件中的行由\n
反对分裂,尽管剩余\r
不会真的造成太大的问题,读...
至于鞋子位:
Shoes.app :title => "Search v0.2", :width => 500, :height => 600 do
@file = File.open 'db.txt', 'rb'
def search(file, query)
file.rewind
file.select {|line| line =~ /#{query}/i }.map {|match| match.chomp }
end
stack :margin => 10 do
@input = edit_line :width => 400
button "search" do
matches = search(@file, @input.text)
@output.clear
@output.append do
matches.empty? ?
title("Nothing found :(") :
title("Results\n")
end
matches.each do |match|
@output.append { para match }
end
end
@output = stack { title "Search for something." }
end
end
您从未定义过@output.matches
或称为您的search()
方法。看看它现在是否有意义。
+0
我爱你,非常感谢你! – Jbod 2011-05-19 15:32:46
所以,只要确保这些代码都可以。例如,'phrase'没有声明,但是你在这段代码中使用它。 – 2011-05-17 20:55:00