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"]
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)
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 returningarray[0..limit]
, to reduce the amount of things happening at a time.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)