First Half. Ruby noob question

roxor

roxor

Posted on April 28, 2022

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

💖 💪 🙅 🚩
roxor
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

Ruby Array Methods
beginners Ruby Array Methods

February 22, 2024

Methods in Ruby
beginners Methods in Ruby

August 21, 2023

Hashes in Ruby
beginners Hashes in Ruby

August 20, 2023

Introdução ao Ruby
beginners Introdução ao Ruby

August 16, 2023