DEV Community

roxor
roxor

Posted on

First Half. Ruby noob question

I'm doing some exercises in ruby, my task was this

Write a method **first_half(array)** that takes in an array and returns a new array containing the first half of the elements in the array. If there is_ an odd number of elements_, return the first half including the middle element.

My solution was this

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

    i += 1
  end

  return new_arr

end

print first_half(["Brian", "Abby", "David", "Ommi"])# => ["Brian", "Abby"]
puts
print first_half(["a", "b", "c", "d", "e"]) # => ["a", "b", "c"]
Enter fullscreen mode Exit fullscreen mode

end this works, but when I change 2.0 to 2.5 editor show only my first two elements "a" and "b". Any explanation why?
Maybe I just overthink this and this is something stupid...

I just want to hear different thoughts

thanks in advance <3

Top comments (3)

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
Collapse
 
jeremyf profile image
Jeremy Friesen
def first_half(array)
  array[0..(1+array.length/2)]
end
Enter fullscreen mode Exit fullscreen mode

(This is from my phone so please check my memory.)

Collapse
 
djuber profile image
Daniel Uber

That's also just about what I would write for my own use, possibly putting the limit = 1 + array.length/2 on a separate line, then returning array[0..limit], to reduce the amount of things happening at a time.