IT Community - Software Programming, Web Development and Technical Support

Ruby BuiltIn functions

This is a discussion on Ruby BuiltIn functions within the Ruby forums, part of the Web Development category; Hi, Can u explain about ruby built-in functions?...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > Ruby

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 03-30-2008, 08:27 PM
bluesky bluesky is offline
D-Web Analyst
 
Join Date: Jun 2007
Posts: 201
bluesky is on a distinguished road
Lightbulb Ruby BuiltIn functions

Hi,
Can u explain about ruby built-in functions?
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 03-30-2008, 08:28 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

A function is "a portion of code within a larger program, performs a specific task".

Functions have many benefits including:

1. reducing the duplication of code in a program (e.g., by replicating useful functionality, such as mathematical functions);
2. enabling reuse of code across multiple programs;
3. decomposing complex problems into simpler pieces (this improves maintainability and ease of extension);
4. improving readability of a program;
5. hiding or regulating part of the program.

Functions are also know under many other names such as subroutines, methods or subprograms

abort
Array
at_exit {...}
binding
block_given?
callcc {| c|...}
caller([ n])
catch( tag) {...}
chomp([ rs=$/])
chomp!([ rs=$/])
chop
chop!
eval( str[, scope[, file, line]])
exec( cmd[, arg...])
exit([ result=0])
exit!([ result=0])
fail(...)
Float( obj)
fork
fork {...}
format( fmt[, arg...])
gets([ rs=$/])
global_variables
gsub( x, y)
gsub( x) {...}
gsub!( x, y)
gsub!( x) {...}
Integer( obj)
lambda {| x|...}
proc {| x|...}
lambda
proc
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 03-30-2008, 08:30 PM
satheesh satheesh is offline
D-Web Programmer
 
Join Date: Aug 2007
Posts: 95
satheesh is on a distinguished road
Default Re: Ruby BuiltIn functions

Hi,
Here are some functions which i know
oad( file[, private=false])
local_variables
loop {...}
open( path[, mode="r"])
open( path[, mode="r"]) {| f|...}
p( obj) print([ arg...])
printf( fmt[, arg...])
proc {| x|...}
putc( c)
puts([ str])
raise(...)
fail(...)
srand([ seed])
String( obj)
syscall( sys[, arg...])
system( cmd[, arg...])
sub( x, y)
sub( x) {...}
trap( sig, cmd)
trap( sig) {...}
untrace_var( var[, cmd]
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 03-30-2008, 08:40 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

abort
Terminate execution immediately, effectively by calling Kernel.exit(1).

Array
Array( arg ) -> anArray
Returns arg .to_a.
Array(1..5) » [1, 2, 3, 4, 5]


at_exit

at_exit { block } -> aProc
Converts block to a Proc object (and therefore binds it at the point of call) and registers it for execution when the program exits. If multiple handlers are registered, they are executed in reverse order of registration.

def do_at_exit(str1)
at_exit { print str1 }
end
at_exit { puts "cruel world" }
do_at_exit("goodbye ")
exit

produces:


goodbye cruel world


binding

binding -> aBinding

Returns a Binding object, describing the variable and method bindings at the point of call. This object can be used when calling eval to execute the evaluated command in this environment. Also see the description of Binding beginning on page 291.

def getBinding(param)
return binding
end
b = getBinding("hello")
eval "param", b » "hello"
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 03-31-2008, 08:49 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

block_given?

block_given? -> true or false


Returns true if yield would execute a block in the current context.

def try
if block_given?
yield
else
"no block"
end
end
try » "no block"
try { "hello" } » "hello"
try do
"hello"
end
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 03-31-2008, 08:50 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

callcc
callcc {| cont | block } -> anObject


Generates a Continuation object, which it passes to the associated block. Performing a cont .call will cause the callcc to return (as will falling through the end of the block). The value returned by the callcc is the value of the block, or the value passed to cont .call. See Continuation on page 294 for more details. Also see Kernel::throw for an alternative mechanism for unwinding a call stack.
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 03-31-2008, 08:51 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

caller
caller( [ anInteger ] ) -> anArray


Returns the current execution stack---an array containing strings in the form ``file:line'' or ``file:line: in `method'''. The optional anInteger parameter determines the number of initial stack entries to omit from the result.

def a(skip)
caller(skip)
end
def b(skip)
a(skip)
end
def c(skip)
b(skip)
end
c(0) » ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
c(1) » ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
c(2) » ["prog:8:in `c'", "prog:12"]
c(3) » ["prog:13"]
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 03-31-2008, 08:52 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

catch
catch( symbol ) {| | block }-> anObject


catch executes its block. If a throw is executed, Ruby searches up its stack for a catch block with a tag corresponding to the throw's symbol. If found, that block is terminated, and catch returns the value given to throw. If throw is not called, the block terminates normally, and the value of catch is the value of the last expression evaluated. catch expressions may be nested, and the throw call need not be in lexical scope.

def routine(n)
puts n
throw :done if n <= 0
routine(n-1)
end


catch(:done) { routine(3) }

produces:

3
2
1
0
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 03-31-2008, 08:55 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

chomp
chomp( [ aString ] ) -> $_ or aString
Equivalent to $_ = $_.chomp(aString). See String#chomp on page 367.

$_ = "now\n"
chomp » "now"
$_»"now"
chomp "ow"»"n"
$_ »"n"
chomp "xxx"»"n"
$_»"n"

chomp!
chomp!( [ aString ] ) -> $_ or nil


Equivalent to $_.chomp!(aString). See String#chomp!

$_ = "now\n"
chomp! » "now"
$_»"now"
chomp! "x"»nil
$_ » "now"
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 04-03-2008, 08:49 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

chop
chop -> aString
Equivalent to ($_.dup).chop!, except nil is never returned. See String#chop!

a = "now\r\n"
$_ = a
chop » "now"
$_ » "now"
chop » "no"
chop » "n"
chop » ""
chop » ""
a » "now\r\n"

chop!
chop! -> $_ or nil


Equivalent to $_.chop!.

a = "now\r\n"
$_ = a
chop! » "now"
chop! » "no"
chop! » "n"
chop! » ""
chop! » nil
$_ » ""
a » ""
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 04-03-2008, 08:50 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

eval
eval( aString [, aBinding [ file [ line ] ] ]) -> anObject


Evaluates the Ruby expression(s) in aString. If aBinding is given, the evaluation is performed in its context. The binding may be a Binding object or a Proc object. If the optional file and line parameters are present, they will be used when reporting syntax errors.

def getBinding(str)
return binding
end
str = "hello"
eval "str + ' Fred'" » "hello Fred"
eval "str + ' Fred'", getBinding("bye") » "bye Fred"

exec
exec( command [, args ])


Replaces the current process by running the given external command. If exec is given a single argument, that argument is taken as a line that is subject to shell expansion before being executed. If multiple arguments are given, the second and subsequent arguments are passed as parameters to command with no shell expansion. If the first argument is a two-element array, the first element is the command to be executed, and the second argument is used as the argv[0] value, which may show up in process listings. In MSDOS environments, the command is executed in a subshell; otherwise, one of the exec(2) system calls is used, so the running command may inherit some of the environment of the original program (including open file descriptors).

exec "echo *" # echoes list of files in current directory
# never get here


exec "echo", "*" # echoes an asterisk
# never get here
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 04-03-2008, 08:52 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

exit
exit( anInteger=0 )


Initiates the termination of the Ruby script by raising the SystemExit exception. This exception may be caught. The optional parameter is used to return a status code to the invoking environment.

begin
exit
puts "never get here"
rescue SystemExit
puts "rescued a SystemExit exception"
end
puts "after begin block"

produces:

rescued a SystemExit exception
after begin block

Just prior to termination, Ruby executes any at_exit functions and runs any object finalizers (see ObjectSpace beginning on page 430).

at_exit { puts "at_exit function" }
ObjectSpace.define_finalizer(self, proc { puts "in finalizer" })
exit

produces:

at_exit function
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 04-03-2008, 08:53 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

exit!
exit!( anInteger=-1 )


Similar to Kernel::exit , but exception handling, at_exit functions, and finalizers are bypassed.

fail

fail
fail( aString )
fail( anException [, aString [ anArray ] ] )


Synonym for Kernel::raise .

fork
fork [{ block } ] -> aFixnum or nil
Creates a subshell. If a block is specified, that block is run in the subshell, and the subshell terminates with a status of zero. Otherwise, the fork call returns twice, once in the parent, returning the process id of the child, and once in the child, returning nil. The child process can exit using Kernel::exit! to avoid running any at_exit functions. The parent process should use Process::wait to collect the termination statuses of its children; otherwise, the operating system may accumulate zombie processes.

fork do
3.times {|i| puts "Child: #{i}" }
end
3.times {|i| puts "Parent: #{i}" }
Process.wait

produces:

Parent: 0
Child: 0
Parent: 1
Child: 1
Parent: 2
Child: 2
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #14 (permalink)  
Old 04-06-2008, 08:35 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

format
format( aString [, anObject ]* ) -> aString


Synonym for Kernel::sprintf .

gets
gets( aString=$/ ) -> aString or nil


Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line. Returns nil at end of file. The optional argument specifies the record separator. The separator is included with the contents of each record. A separator of nil reads the entire contents, and a zero-length separator reads the input one paragraph at a time, where paragraphs are divided by two consecutive newlines. If multiple filenames are present in ARGV, gets(nil) will read the contents one file at a time.

ARGV << "testfile"
print while gets

produces:

This is line one
This is line two
This is line three
And so on...
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #15 (permalink)  
Old 04-06-2008, 08:37 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

global_variables
global_variables -> anArray


Returns an array of the names of global variables.

global_variables.grep /std/ » ["$stdin", "$stderr", "$stdout"]

gsub
gsub( pattern, replacement ) -> aString
gsub( pattern ) {| | block }

-> aString


Equivalent to $_.gsub..., except that $_ receives the modified result.

$_ = "quick brown fox"
gsub /[aeiou]/, '*' »"q**ck br*wn f*x"
$_ »"q**ck br*wn f*x"
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #16 (permalink)  
Old 04-06-2008, 08:48 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

load
load( aFileName, wrap=false ) -> true


Loads and executes the Ruby program in the file aFileName. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:. If the optional wrap parameter is true, the loaded script will be executed under an anonymous module, protecting the calling program's global namespace. Any local variables in the loaded file will not be propagated to the loading environment.

gsub!

gsub!( pattern, replacement ) -> aString or nil
gsub!( pattern ) {| | block }

-> aString or nil


Equivalent to Kernel::gsub , except nil is returned if $_ is not modified.

$_ = "quick brown fox"
gsub! /cat/, '*' » nil
$_ » "quick brown fox"
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #17 (permalink)  
Old 04-06-2008, 08:50 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

local_variables
local_variables -> anArray


Returns the names of the current local variables.

fred = 1
for i in 1..10
# ...
end
local_variables »["fred", "i"]

loop
loop {| | block }
Repeatedly executes the block.

loop {
print "Input: "
break if !gets or $_ =~ /^qQ/
# ...
}
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #18 (permalink)  
Old 04-07-2008, 08:04 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

open
open( aString [, aMode [ perm ] ] ) -> anIO or nil
open( aString [, aMode [ perm ] ] ) {| anIO | block }

-> nil


Creates an IO object connected to the given stream, file, or subprocess.

If aString does not start with a pipe character (``|''), treat it as the name of a file to open using the specified mode defaulting to ``r'' (see the table of valid modes on page 326). If a file is being created, its initial permissions may be set using the integer third parameter.

If a block is specified, it will be invoked with the File object as a parameter, and the file will be automatically closed when the block terminates. The call always returns nil in this case.

If aString starts with a pipe character, a subprocess is created, connected to the caller by a pair of pipes. The returned IO object may be used to write to the standard input and read from the standard output of this subprocess. If the command following the ``|'' is a single minus sign, Ruby forks, and this subprocess is connected to the parent. In the subprocess, the open call returns nil. If the command is not ``-'', the subprocess runs the command. If a block is associated with an open("|-") call, that block will be run twice---once in the parent and once in the child. The block parameter will be an IO object in the parent and nil in the child. The parent's IO object will be connected to the child's $stdin and $stdout. The subprocess will be terminated at the end of the block.

open("testfile") do |f|
print f.gets
end

produces:

This is line one

Open a subprocess and read its output:

cmd = open("|date")
print cmd.gets
cmd.close

produces:

Sun Jun 9 00:19:39 CDT 2002

Open a subprocess running the same Ruby program:


f = open("|-", "w+")
if f == nil
puts "in Child"
exit
else
puts "Got: #{f.gets}"
end

produces:

Got: in Child

Open a subprocess using a block to receive the I/O object:

open("|-") do |f|
if f == nil
puts "in Child"
else
puts "Got: #{f.gets}"
end
end

produces:


Got: in Child
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #19 (permalink)  
Old 04-07-2008, 08:05 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

p
p( [ anObject ]+ ) -> nil


For each object, directly writes anObject.inspect followed by the current output record separator to the program's standard output. p bypasses the Ruby I/O libraries.

p self

produces:

main
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #20 (permalink)  
Old 04-07-2008, 08:06 PM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: Ruby BuiltIn functions

print
print( [ anObject ]* ) -> nil


Prints each object in turn to $defout. If the output field separator ($,) is not nil, its contents will appear between each field. If the output record separator ($\) is not nil, it will be appended to the output. If no arguments are given, prints $_. Objects that aren't strings will be converted by calling their to_s method.

print "cat", [1,2,3], 99, "\n"
$, = ", "
$\ = "\n"
print "cat", [1,2,3], 99

produces:


cat12399
cat, 1, 2, 3, 99

printf

printf( anIO, aString [, anObject ]* ) -> nil
printf( aString [, anObject ]* ) -> nil
Equivalent to:anIO. write sprintf( aString, anObject ...)
or
$defout.write sprintf( aString, anObject ...)
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Is Ruby for Web? S.Vinothkumar Ruby 6 11-20-2007 01:25 AM
What are Virtual Functions? How to implement virtual functions in "C"? Sabari C and C++ Programming 4 09-10-2007 10:35 PM
What Is RUBY? theseokit Ruby 7 03-12-2007 11:43 PM
Ruby within .NET? econwriter5 Ruby 0 03-07-2007 05:02 PM
Ruby IDE drecko Ruby 0 02-16-2007 12:11 AM


All times are GMT -7. The time now is 02:00 AM.