Colin Marshall Colin Marshall - 8 months ago 68
Ruby Question

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 =
arr = ["a", "b", "c"]

Answer Source

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)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download