Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

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
like image 379
Colin Marshall Avatar asked Sep 04 '25 01:09

Colin Marshall


2 Answers

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.

like image 55
Pend Avatar answered Sep 07 '25 11:09

Pend


You can also use .first for the first element in the array, and .last for the last element in an array.

def first_and_last(arr)
  [arr.first, arr.last]
end 

p first_and_last([1,2,3,4,5,6])

Or....

def first_and_last(arr)
   [arr[0], arr[-1]]
end 

p first_and_last([1,2,3,4,5,6])
like image 36
Jacob Moore Avatar answered Sep 07 '25 12:09

Jacob Moore