Search code examples
arraysruby

Return only the first and last items of an array in Ruby


I need to create a method named first_and_last. It should use one argument, an Array, and return a new Array with only the first and last objects of the argument.

Here is what I have so far, but the method seems to ignore the initial argument and just create a new array.

def first_and_last(a)
  arr = Array.new
  arr = ["a", "b", "c"]  
end

Solution

  • You can use the values_at() method to get the first and last elements in an array like this:

    def first_and_last(input_array)
      input_array.values_at(0,-1)
    end
    

    Depending on what behavior you're looking for, it might not work on arrays with 1 or 0 elements. You can read more about the method here.