I'm doing some Ruby excercises. My goal is to create a method which reproduces the first and last number of an array.
我正在做一些Ruby练习。我的目标是创建一个再现数组的第一个和最后一个数字的方法。
My way of thinking was:
我的想法是:
#create array
a = [1,2,3,4]
#create method
def lastFirst
return a[0,3]
end
#call the method with an array
lastFirst(a)
But this produces [1,2,3]
instead of what I want, which is (1,3)
.
但这会产生[1,2,3]而不是我想要的,这是(1,3)。
Any thoughts on what I'm doing wrong?
对我做错了什么的想法?
2 个解决方案
#1
5
a[0,3]
means get 3 elements starting from offset 0.
意味着从偏移0开始获得3个元素。
Try this:
def lastFirst(a)
[a.first, a.last]
end
#2
4
Write it using the Array#values_at
method:
使用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]
#1
5
a[0,3]
means get 3 elements starting from offset 0.
意味着从偏移0开始获得3个元素。
Try this:
def lastFirst(a)
[a.first, a.last]
end
#2
4
Write it using the Array#values_at
method:
使用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]