Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Some useful built-in Functions in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 334
    Comment on it

    1) at_exit { code to be executed}
    This method starts the execution of the code when the program exits.
    For Example:

    puts "Begining of execution"
    at_exit do
      puts "Inside at_exit"
    end
    puts "End of execution"

    Output:

    Begining of execution
    End of execution
    Inside at_exit

     

    2) autoload(classname, file_path)
    It loads the class from the given filename. Here classname can be a string or symbol. Autoload works like require but the difference is that the file is only required when the constant is accessed, which can speed up your program.

    Let's say you have a file called example.rb containing the following code:

    puts "Welcome user!"
    
    class MyClass
    end

     

    Now open irb and use require to load the example.rb

    irb(main):001:0> require 'example'
    Welcome user!
    => true

     

    Now again open irb and use autoload:

    irb(main):001:0> autoload :MyClass, 'example'
    => nil
    irb> MyClass
    Welcome user!
    => MyClass

     

    3) eval(str)
    To evaluate and compile a string you can do it by using eval. Its return value is the value of the last expression of the program.
    For example:

    p eval("1 + 1")   # 2

     

    we can also refer to a variable in its scope from inside of a string to `eval`.

    first_var = 5
    @second_var = 6
    p eval("first_var + @second_var")   # 11

     

    4) chop()
    Chop method returns the value of string after removing its last character. If the string ends with rn, both characters are removed.

    For example:

    "Apple\r\n".chop   #=> "Apple"
    "Apple\n\r".chop   #=> "Apple\n"
    "Apple\n".chop     #=> "Apple"

     

    5) proc {| x|...}
    The block is been converted into Pro object by Proc converts. Proc objects are blocks of code that have been bound to a set of local variables.
    For example:

    proc_1 = Proc.new { |x| puts x*2 }
    [1,2,3].each(&proc_1)
    
    proc_2 = Proc.new { puts "Hello World" }
    proc_2.call

     

    6) sleep( 10 )
    Suspends program execution for seconds specified. If the second isn't specified, the program is suspended forever.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: