現在我們將前面的一些樣本程式的代碼坼開來分析一下. 下面的例子出現在簡單的例子一節. def fact(n) if n == 0 1 else n * fact(n-1) end end print fact(ARGV[0].to_i), "\n" 因為是第一次解釋,我們將逐行分析. def fact(n) 第一行,def
讓我們寫一個計算階乘的函數.對於階乘的數學定義如下: n! = 1 (當 n==0 時) = n * (n-1)! (其它情況) 在Ruby裡,可以這樣來寫: 複製代碼 代碼如下:def fact(n) if n == 0 1 else n * fact(n-1) end end 你可能會發現 end
讀取一個檔案,將其列印出來:lines = File.open('dom.js').readlinesputs "======================="lines.each { |line| puts(line)}或者:File.open("dom.js") do |file| while line = file.gets puts line endend後一種能確保檔案用完後被關閉。向目標檔案追加內容:file =
你有多少種方式建立一個方法?大多數人想到的可能是def 關鍵字 Ruby代碼 #普通方法 def tele_you puts "I am Anleb" end #普通方法def tele_you puts "I am Anleb"endRuby代碼 #定義單件方法 n="Anleb" def n.tell_you puts "I am #{self}" end n.tell_you #定義單件方法n="Anleb"def
1.建立檔案夾 Dir.new %%1 Dir::mkdir #不指定目錄全名稱時,預設為工作目錄 Dir::chdir() 改變當前指令碼工作目錄 FileUtils.mkdir 'test' file = File.new("cmd.txt") file.each do |line| puts line if line =~ /target/ end 2.建立檔案 改變當前根目錄 Dir.chdir("/home/guy/sandbox/tmp")