Search code examples
rubyarraysassertsymbols

Symbols inside Arrays (Ruby)


I'm doing some koans exercises and am having trouble understanding the values returned with symbols inside arrays. Can someone explain why the following are equal or suggest a good article on the subject that I could infer the proper knowledge from??? This is different than with strings:

    array = [:peanut, :butter, :and, :jelly]

     assert_equal [:and, :jelly], array[2,2]
     assert_equal [:and, :jelly], array[2,20]
     assert_equal [:jelly, :peanut], array[4,0]
     assert_equal [:jelly, :jelly], array[4,100]

Solution

  • Check out now and always documentation: ary[start, length] → new_ary or nil.

    It returns subarray. Here 'start' is the index of first element in you array, length stands for length of subarray. If length >= ary.size - start you will get subarray from start to end of ary.

    In your case:

    array = [:peanut, :butter, :and, :jelly]   
    array[2, 2] #=>  [:and, jelly]
    array[2,20] #=>  [:and, jelly]
    array[4, 0] #=> []; length of empty array is 0!
    array[4, 100] #=> []; well, okay. There's no element with index equal to 4.
                 # but holy documentation says "empty array is returned when 
                 # the starting index for an element range is at the end of 
                 # the array."
    array[5, 0]  #=> nil; there's nothing at 5th position.
    array[-2, 2] #=> [:and, jelly]; :)
    

    You told that strings inside arrays act not like this? You must be facing black magic. May you provide me an example?