First Half. Ruby noob question
roxor
Posted on April 28, 2022
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
💖 💪 🙅 🚩
roxor
Posted on April 28, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
beginners More Ruby newbie time: The importance of 'making the invisible visible' as a beginner (featuring the Date class)
November 14, 2023