Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Arrays and Hash In Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 603
    Comment on it

    Ruby's arrays and hashes collections having indexes. They can also be said as indexed collections.

    Arrays and hashes store collections of objects which can be accessed using a key.

    Both arrays and hashes grow as needed to hold new elements.

    It's more efficient to access array elements, but hashes provide more flexibility.

    Any particular array or hash can hold objects of differing types; you can have an array containing an integer, a string, and a floating point number.

    Below are array examples which would help you to understand Arrays better : 

    a=[1,'car',5.94]  #array with three elements
    # access the first element
    a[0]
    
    1
    # set the third element
    a[2]=nil
    # dump out the array
    a
    
    [1, "car", nil]

    arrays can be accessed like this

    arr = [1, 2, 3, 4, 5, 6]
    arr[2]    #=> 3
    arr[100]  #=> nil
    arr[-3]   #=> 4
    arr[2, 3] #=> [3, 4, 5]
    arr[1..4] #=> [2, 3, 4, 5]

    A Hash is a collection of key-value pairs. Ruby hashes are similar to arrays.

     A hash literal uses braces rather than square brackets. The literal must supply two objects for every entry: one for the key, the other for the value.

    It is similar to an Array, but difference is that indexing in hashes is done from arbitrary keys of any object type, not an integer index.

    Example of hash is given below:

    h = {'Tom' => 'Cruise', 'Jhon' => 'Mayor', 'Taylor' => 'Swift', 12 => 'hello'}  
    puts h.length  # 4  
    puts h['Tom']  # 'Cruise'  
    puts h  
    puts h[12]  
    

    and the output would be

    4  
    Cruise  
    {"Tom"=>"Cruise", "Jhon"=>"Mayor", "Taylor"=>"Swift", 12=>"hello"}  
    hello  
    >Exit code: 0  

    So this is how array and hashes work in Ruby.

    Hope this blog was helpful to understand arrays and hashes.

 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: