Ruby 模板和文件讀寫筆記


基本上,花費了差不多都四小時,在 google 大神的幫助之下,終於都有了初部的結論和基本的理解了..不過其實問題最多的應該就是在於讀寫純文本部份吧,雖然說不上是太難,但還真學會了不少東西..記錄一下..

首看,不知道有沒有測試錯誤, Ruby 在編寫後,都是以一行一行直讀的,而不會去在讀到那行時跳到下面幫你找想要呼叫的 def 函式
如下面 :

無法顯示 abc 這值 ? 要將 puts calldef 放到 def 後才可以呼叫 ?

1
2
3
4
5
puts calldef()

def calldef
return "abc"
end

再者,關於以下代碼,這是仿我讀寫部份的一個例子,會發現沒有任何輸出..好奇怪..如果用 {} 包著的就不可以回傳 ? 是我問題 ?

1
2
3
4
5
6
7
8
9
10
puts backdata

def backdata
File.open("d.txt","r") {
File.close;

return "0"
}
return "1"
end

另外,關於模版方面,有一個怪怪的情況..就是當資料是 Array 時用,會發現陣列自動走了上去,而不是原來的預計位置 ? 是我問題 ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 這是 test.rb
require 'erb'

template=IO.read(File.dirname(__FILE__)+"/test.html")
template=ERB.new(template)

test_arr = ["this is a test 1", "this is a test 2"]

puts "Content-type: text/html\r\n\r\n"
puts template.result

# 這是 test.html
<html>
<head></head>
<body>
<div>This is a test erb template</div>
<%
test_arr.each{|val|
puts val,"<br />"
}
%>
</body>
</html>

PS : 以上全都為仿我學習時寫的代碼而寫的片段,以上未經測試,只作為日後查看之用,請留意 = =