在《Ruby基礎教程》中,作者爲了詳細說明對文本的操作舉了一個非常生動的例子。我在學習的時候有一些地方不太理解,標記如下,與大家共勉。
Encoding.default_external = Encoding.find('utf-8')
pattern = Regexp.new(("(.{0,10})("+ARGV[0]+")(.{0,10})").to_s.encode('utf-8'))
filename = ARGV[1]
count = 0
File.open(filename) do |file|
file.each_line do |line|
line.scan(pattern) do |s|
prefix_len = 0
s[0].each_char do |ch|
if ch.ord < 128
prefix_len += 1
else
prefix_len += 2
end
end
space_len = 20 - prefix_len
puts "#{" "*space_len}#{s[0]}<<#{s[1]}>>#{s[2]}"
count += 1
end
end
end
puts "count: #{count}"
1.關於正則表達式
Ruby中定義了sub,gsub和scan三個方法來接收正則表達式,上面示例中使用了scan方法。
2.關於ch.ord方法
可以獲取字符編碼的碼位。本例中,由於碼位小於 128 時即爲 ASCII 碼,這時將長度加 1,除此以外的情況下則加 2,這些都是爲了確定空白個數 space_len
以確保 20 個字符。然後再在 s[0]
之前留出與字符數相應的空白,這樣輸出結果就整齊多了。