[ruby] 第一支 ruby 程式
寫 paper 寫到快瘋掉時,就會想做點奇怪的事。
早上翻到 Tsung 的文章,有 sed/perl 寫的 Y! dictionary script,然後手也癢了起來。用 python 寫嗎?可是感覺失去挑戰性了,畢竟已經是初學者的身份了,拿這個寫就沒有學習的快樂了。所以就挑上 ruby 啦,反正也是照著彥明的 script 直翻,大概就像這樣啦:
完整的程式在這裡。唔,因為 ports 裡沒有 term-ansicolor,所以我也順手送上去了。
def ydict (shift)
raise ArgumentError, ‘Must specify word’ if shift == nil
include Term::ANSIColor
Net::HTTP.start(‘tw.dictionary.yahoo.com‘, 80) {|http|
response = http.get(‘/search?p=’ + shift)
@html = response.body
}
if ENV[‘LC_CTYPE’] =~ /Big5/
@html = Iconv.new(‘big5′, ‘utf-8‘).iconv(@html)
end
i = 0
html = @html.gsub /r/, ""
html = html.gsub /n/, ""
if html =~ /<em class="warning">/
if html =~ /<em class="warning">.*?>(S+)<.*?</em>/
q = $1;
print bold , yellow , "nERROR: ", shift , " -> " , q , "n", reset
return ydict(q)
else
print bold , yellow , "ERROR: ", shift , "n", reset
return
end
end
print bold , yellow , "n" + shift + "n" , reset
while html =~ /<div class=p(w+)>(.*?)</div>/i
type = $1
line = $2
html = $’
$reset = reset
line = line.gsub /^s+/, ""
line = line.gsub /s+$/, ""
if type == ‘cixin’
i = 0
$color = bold, red
elsif type == ‘chi’ or type == ‘eng’
$color = cyan;
$reset = reset + $color
line = "t" + line
elsif type == ‘explain’
i = i + 1
line = i.to_s + " " + line
else
color = bold, blue
next
end
line = line.gsub /<b>/, bold
line = line.gsub /</b>/, $reset
line = line.gsub /<[^>]+>/, $reset
print $color , line + "n" , reset
end
puts ""
end
raise ArgumentError, ‘Must specify word’ if shift == nil
include Term::ANSIColor
Net::HTTP.start(‘tw.dictionary.yahoo.com‘, 80) {|http|
response = http.get(‘/search?p=’ + shift)
@html = response.body
}
if ENV[‘LC_CTYPE’] =~ /Big5/
@html = Iconv.new(‘big5′, ‘utf-8‘).iconv(@html)
end
i = 0
html = @html.gsub /r/, ""
html = html.gsub /n/, ""
if html =~ /<em class="warning">/
if html =~ /<em class="warning">.*?>(S+)<.*?</em>/
q = $1;
print bold , yellow , "nERROR: ", shift , " -> " , q , "n", reset
return ydict(q)
else
print bold , yellow , "ERROR: ", shift , "n", reset
return
end
end
print bold , yellow , "n" + shift + "n" , reset
while html =~ /<div class=p(w+)>(.*?)</div>/i
type = $1
line = $2
html = $’
$reset = reset
line = line.gsub /^s+/, ""
line = line.gsub /s+$/, ""
if type == ‘cixin’
i = 0
$color = bold, red
elsif type == ‘chi’ or type == ‘eng’
$color = cyan;
$reset = reset + $color
line = "t" + line
elsif type == ‘explain’
i = i + 1
line = i.to_s + " " + line
else
color = bold, blue
next
end
line = line.gsub /<b>/, bold
line = line.gsub /</b>/, $reset
line = line.gsub /<[^>]+>/, $reset
print $color , line + "n" , reset
end
puts ""
end
ydict(ARGV[0])
看起來好像可以再簡化(比如說 “+=” 或 “.=” 這東西不知道有沒有相對應的),不過第一個 ruby 程式就不用太講究啦。 ![]()














