DEV Community

Discussion on: First Half. Ruby noob question

Collapse
 
djuber profile image
Daniel Uber • Edited

I think dividing by 2.5 isn't what you want to do. I suspect you're trying to handle a situation like "array of length 5", where you want items 0, 1, and 2 (not only 0 and 1).

It looks like your code already works as expected: given an array of length 5 I get back the first 3 elements, since 0, 1, and 2 are all less than 5/2.0, given an array of length 6 I get back 3 elements as well (2 < 6/2.0, 3 is not less than 6/2.0).

You might approach this by separating the cases for odd and even length arrays, and using integer divisors instead, or by using the fact that integer division rounds down (and just adding one to the length to accomodate)

def first_half(array)
  new_arr = []
  i = 0
  while i < (array.length + 1) / 2
    new_arr << array[i]

    i += 1
  end

  return new_arr

end


# test with arrays of size 0, 1, 2, 3, 4, expecting results of size 0, 1, 1, 2, 2
first_half []
=> []                        
first_half [1]
=> [1]                        
first_half [1, 2]
=> [1]                           
first_half [1, 2, 3]
=> [1, 2]                           
first_half [1, 2, 3, 4]
=> [1, 2]                              
Enter fullscreen mode Exit fullscreen mode