2011-05-17 107 views
0

我有一個簡短的腳本,它使用正則表達式搜索文件中用戶輸入的特定短語。基本上,它是一個簡單的搜索框。紅寶石鞋搜索框

我現在試圖讓這個搜索框有一個圖形用戶界面,這樣用戶可以輸入一個框,並將他們的匹配「提醒」給他們。

我是使用紅寶石鞋的新手,並且在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 

非常感謝

+0

所以,只要確保這些代碼都可以。例如,'phrase'沒有聲明,但是你在這段代碼中使用它。 – 2011-05-17 20:55:00

回答

1

那麼,對於初學者來說,第一個碼位可以被整理。

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 endwhile 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