rengfin - ruby

rane 19.06.06 08:34

terminaalissa ajettava sanakirja. hakee sanat osoitteesta http://efe.scape.net/

 Tekstiversio  Arvo: 0 (4 ääntä)  Äänestä: +  -
# rengfin.rb - rane
# v0.2 21.6.2006
# usage: ruby rengfin.rb
# type the word you wish to look up on online dictionary (http://efe.scape.net)
# 21.6.2006 v0.2 - fixed the problem with scandinavian characters
# 19.6.2006 v0.1 - initial release 
require 'net/http'

class Fixnum 
  def max(num)
    self > num ? num : self
  end
end

def windows_cmd(str)
  char_table = { 132 => 228,  148 => 246 }
  str = str.split(//)
  str.each do |x|
    if char_table.has_key?(x[0])
      x[0] = char_table[x[0]]
    end
  end
  str = str.join
end

print "Word to look up: "
word = gets.chomp
print "\n"

word = windows_cmd(word)

http = Net::HTTP.new('efe.scape.net', 80)
path = '/index.php'

# GET request -> so the host can set his cookies
resp, data = http.get(path, nil)
cookie = resp.response['set-cookie']

data = 'criteria='+word+'&page=1'
data = http.post(path, data, {"Content-Type" => "application/x-www-form-urlencoded"})
foo = data.body.scan(%r{<tr><td>[0-9]+</td><td nowrap>&nbsp;&nbsp;(.*?)&nbsp;</td><td nowrap>&nbsp;(.*?)</td></tr>}m)
bar = data.body.scan(%r{<tr><td colspan=3 bgcolor="#EEEEEE">\(([0-9]+)\) Results for (.*?) word: "(.*?)"</td></tr>}m)

unless foo.length > 0
  puts "no results"
  exit
end

bar[0][0] = bar[0][0].to_i.max(10)
puts "#{bar[0][0]} result(s) for #{bar[0][1]} word '#{bar[0][2]}'"
bar[0][0].to_i.times do |i|
  print "|"+foo[i][0]
  (40-foo[i][1].to_s.length-foo[i][0].to_s.length).times { print "-"}
  print foo[i][1]+"|"
  print "\n"
end
print "\n"
bar[0][0].to_i.times do foo.shift end
  
if foo.length > 0 then
  bar[1][0] = bar[1][0].to_i.max(10)
  puts "#{bar[1][0]} result(s) for #{bar[1][1]} word '#{bar[1][2]}'"
  bar[1][0].to_i.times do |i|
    print "|"+foo[i][0]
    (40-foo[i][1].to_s.length-foo[i][0].to_s.length).times { print "-"}
    print foo[i][1]+"|"
    print "\n"
  end
end
gets

editoitu: 08:46 19.6.06
rane 08:34 19.6.06 
rane@kahiseva:~$ ruby rengfin.rb
Word to look up: murea

1 result(s) for finnish word 'murea'
|murea------------------------tender|

rane@kahiseva:~$ ruby rengfin.rb
Word to look up: kuha

2 result(s) for finnish word 'kuha'
|kuha---------------------pike perch|
|kuha---------------------pike-perch|
cyndis 23:34 23.6.06 
Arraylla on metodi max, joten voit tehdä [x,y].max, ja tuon viivoituksen voi tehdä metodeilla String#rjust ja String#ljust, jotka dokumentaatiosta poiketen ottavat toisena parametrina käytettävän täyttömerkin. Tuon replacen olisi myös voinut tehdä String#gsubilla tyyliin str.gsub(132.chr,228.chr).gsub(148.chr,246.chr).
kedis 20:24 6.7.06 
Mikäpä avuksi, kun heittää seuraavanlaista herjaa:
sana.rb:41: undefined method `body' for #<Array:0x402afca4> (NameError)

editoitu: 20:51 10.7.06
rane 20:47 10.7.06 
ilmeisesti sivua ei saada haettua
edit: päivitin koodia hieman, edellinen versio ei toiminut 1.8.4 versiolla.