if语句带语法错误的方法

时间:2014-12-18 15:56:54

标签: ruby-on-rails ruby

我正在做一些Ruby练习。我的目标是创建一个方法来重现数组的第一个和最后一个数字。

我的想法是:

#create array
a = [1,2,3,4]
#create method
def lastFirst
   return a[0,3]
end
#call the method with an array
lastFirst(a)

但这会产生[1,2,3]而不是我想要的,(1,3)

对我做错了什么的想法?

2 个答案:

答案 0 :(得分:5)

a[0,3]

表示从偏移0开始获取3个元素。

试试这个:

def lastFirst(a)
  [a.first, a.last]
end

答案 1 :(得分:4)

使用Array#values_at方法编写它:

#create array
a = [1,2,3,4]
#create method
def last_first(a)
  a.values_at(0, -1)
end
#call the method
last_first(a) # => [1, 4]
相关问题