Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between first & take in Ruby Arrays

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 203
    Comment on it

    Both first & take are applied on the ruby objects, they return the requested number of elements from the Array. There are some differences between them, and i have explained the major ones over here.

    1) The method take always accepts an argument, and that argument is the number of elements to be returned from the ruby Array, if we don not supply an argument it gives us error.

    >> a = [1,2,3,4,5]
    
    >> a.take(4)
    => [1, 2, 3, 4]
    
    >> a.take
    ArgumentError: wrong number of arguments (0 for 1)
        from (irb):2:in `take'
    

    Whereas, first can be used with an argument or without an argument. If used without an argument, it returns the first element of the array. If used with an argument, it returns the specified number of elements from the beginning of the array.

    >> a = [1,2,3,4,5]    
    >> a.first
    => 1
    >> a.first(4)
    => [1, 2, 3, 4]
    

    2) If the array is empty the take method return an empty array.

    >> a = []
    
    >> b = a.take(2)
    => []
    

    While in case of first method, if it is called direclty on an empty array without any argument it will return nil

    >> a = []
    >> c = a.first
    => nil
    

    Though if we are using first with an argument on an empty array it returns an empty array.

    >> a = []
    >> c = a.first(2)
    => []
    

 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: