Ruby 內建函式



由於Kernel模組被Object類包含,因此它的方法在Ruby程式的任何地方都可用。它們可以在沒有接收者的情況下被呼叫(函式形式)。因此,它們通常被稱為函式。

數字函式

以下是與數字相關的內建函式列表。它們應按如下方式使用:

#!/usr/bin/ruby

num = 12.40
puts num.floor      # 12
puts num + 10       # 22.40
puts num.integer?   # false  as num is a float.

這將產生以下結果:

12
22.4
false

浮點數函式

數學函式

轉換欄位說明符

函式sprintf( fmt[, arg...]) 和 format( fmt[, arg...])返回一個字串,其中 arg 根據 fmt 進行格式化。格式化規範與 C 程式語言中 sprintf 的格式化規範基本相同。fmt中的轉換說明符(% 後跟轉換欄位說明符)將被相應引數的格式化字串替換。

以下是用法示例:

#!/usr/bin/ruby

str = sprintf("%s\n", "abc")   # => "abc\n" (simplest form)
puts str 

str = sprintf("d=%d", 42)      # => "d=42" (decimal output)
puts str 

str = sprintf("%04x", 255)     # => "00ff" (width 4, zero padded)
puts str 

str = sprintf("%8s", "hello")  # => " hello" (space padded)
puts str 

str = sprintf("%.2s", "hello") # => "he" (trimmed by precision)
puts str 

這將產生以下結果:

abc
d = 42
00ff
   hello
he

測試函式引數

函式test( test, f1[, f2])執行由字元test指定的以下檔案測試之一。為了提高可讀性,您應該使用 File 類方法(例如,File::readable?)而不是此函式。

以下是用法示例。假設 main.rb 存在並具有讀、寫許可權,但沒有執行許可權:

#!/usr/bin/ruby

puts test(?r, "main.rb" )   # => true
puts test(?w, "main.rb" )   # => true
puts test(?x, "main.rb" )   # => false

這將產生以下結果:

true
false
false
廣告

© . All rights reserved.