Ruby Array - Index, Part 2

  • + 0 comments

    You can solve this Ruby challenge with a few simple lines. Here’s the complete and correct code for the problem:

    def init_array() create and return array with 10 elements (integer) in it [9, 7, 6, 5, 4, 6, 7, 1, 2, 3] end

    def neg_pos(arr, index) return the element of the array at the position index from the end of the list arr[-index] end

    def first_element(arr) return the first element of the array arr.first end

    def last_element(arr) return the last element of the array arr.last end

    def first_n(arr, n) return first n elements of the array arr.take(n) end

    def drop_n(arr, n) drop first n elements of the array and return the rest arr.drop(n) end

    This uses Ruby’s built-in methods exactly as shown in the problem description — arr[-index], arr.first, arr.last, arr.take(n), and arr.drop(n). It should pass all the tests on HackerRank.