Ruby – Built-in Functions

  • Post author:
  • Post category:Ruby
  • Post comments:0 Comments

Since the Kernel module is included by Object class, its methods are available everywhere in the Ruby program. They can be called without a receiver (functional form). Therefore, they are often called functions.A complete list of Built-in Functions is given here for your reference −

Functions for Numbers

Here is a list of Built-in Functions related to number. They should be used as follows −Live Demo

#!/usr/bin/ruby

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

This will produce the following result −

12
22.4
false

Assuming, n is a number −

Functions for Float

Here is a list of Ruby Built-in functions especially for float numbers. Assuming we have a float number f −

Functions for Math

Here is a list of Ruby Built-in math functions −

Conversion Field Specifier

The function sprintf( fmt[, arg…]) and format( fmt[, arg…]) returns a string in which arg is formatted according to fmt. Formatting specifications are essentially the same as those for sprintf in the C programming language. Conversion specifiers (% followed by conversion field specifier) in fmt are replaced by formatted string of corresponding argument.The following conversion specifiers are supported by Ruby’s format −

Following is the usage example −Live Demo

#!/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 

This will produce the following result −

abc
d = 42
00ff
   hello
he

Test Function Arguments

The function test( test, f1[, f2]) performs one of the following file tests specified by the character test. In order to improve readability, you should use File class methods (for example, File::readable?) rather than this function.Here are the file tests with one argument −File tests with two arguments are as follows −

Following is the usage example. Assuming main.rb exist with read, write and not execute permissions −Live Demo

#!/usr/bin/ruby

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

This will produce the following result −

true
false
false

Leave a Reply