Stuck on how to use .first and .last on an array

I need to create a method named first_and_last. Take one argument - an array - and return a new array with only the first and last objects.

My attempt:

def first_and_last(a)
  first_and_last = [1,2,3]
  first_and_last.last.first
end

      

Here's where I'm confused, it also says that I need the strings "a" and "d" along with numbers. However, there are 3 numbers and 4 lines. I figured 0 would be .first

numbers.

describe "first_and_last" do
      it "creates new array with numbers" do
        expect( first_and_last([1,2,3]) ).to eq([1,3])
      end
      it "creates new array with strings" do
        expect( first_and_last(["a", "b", "c", "d"]) ).to eq(["a", "d"])
      end
    end

      

I don't understand how to include in the array both 1,2,3

and strings "a", "b", "c", "d"

using .first

and.last

Thanks in advance for your help!

+3


source to share


3 answers


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

      



+5


source


Your question is not clear. You can implement it like this.



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

      

+4


source


Since you already have the correct answer from Mori, let's break down why your code isn't working.

Your method takes one parameter, but you manually assign the variable first_and_last

.

When you call .last

on an array, it will give you the last element, so this part of your code is somewhat correct first_and_last.last

. But when you add .first

to a variable, you are actually calling .first

in FixNum because the last element of the array was a number. Check out the code for more tutorials on arrays.

EDIT:

   #ATTN ONE LINER AHEAD
   #Credit to Mori..
   def first_and_last(a); [a.first,a.last]; end

      

+1


source







All Articles