Array Index Play

Problem: Write a method that returns an Array that contains every other element of the passed Array argument. The values in the returned list should be those values that are in the 1st, 3rd, 5th, and so on elements of the argument Array.

The problem wants you to select the even indices in the given array and return only even indices (arrays are 0 indexed so [index 0 = 1st]).

This problem gave me some issues initially but I was eventually able to get it down to two lines of code.

# Solution Attempt 1:
def oddities(array)
cont_arr = [] # create a container to hold values
index = 0 # set initial value for my index to 0.. change to 1 for odd
while index < array.length # using a while iterator to loop
cont_arr.push(array[index]) # during each iteration push value # into cont_arr
index += 2 # update the index variable value
cont_arr # Finally return my cont_arr with values.
Solution Attempt 2:
def oddities2(array)
hldr_arr = [] # instantiate holder array
# loop with each method (values & index)
array.each.with_index do |v, i|
# push value to array if index even
hldr_arr.push(v) if i.even?
hldr_arr # implicit return your holder array
# could have shorten this to
array.each.with_index { |v, i| hldr_arr.push(v) if i.even? }
Solution Attempt 3:
def oddities5(array)
Declared a variable to hold return. Used map + with_index method. returned array value to map method if index is even (map method returns nil if no return)
y = { |v, i| v if i.even? }
Delete all nils inserted into array
y.delete_if {|x| x.nil?)
Same solution except using reject method and passing it .nil? as a proc
def oddities6(array)
z = { |v, i| v if i.even? }

This problem is a great workout for some Array data structure tinkering.