We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Ruby Array - Index, Part 2
You are viewing a single comment's thread. Return to all 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
indexfrom the end of the list arr[-index] enddef 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.