[英]Find the 2nd element of array
I don't understand how this isn't working. 我不明白这是怎么回事。 The program is supposed to take instance method second in the class Array and return the 2nd object in the array
该程序应该在类Array中获取第二个实例方法,并返回数组中的第二个对象
class Array
def second(*arr)
arr.length <= 1 ? nil : arr[1]
end
end
#Test cases
Test.assert_equals(Array([1, 2, 3]), 2,) #Getting nil
Test.assert_equals(Array([]), nil) #passes
Test.assert_equals(Array([1]), nil) #passes
What am I doing wrong? 我究竟做错了什么? if I remove class Array and test on second it works fine?
如果我删除类Array并在第二次测试它工作正常?
Why use *arr
? 为什么要使用
*arr
? If you're monkey-patching Array
, then use self
: 如果你正在修补
Array
,那么使用self
:
class Array
def second
self.length <= 1 ? nil : self[1]
end
end
p [1,2,3].second #=> 2
p [1].second #=> nil
p [].second #=> nil
In answer to what you're doing wrong, your code as written doesn't need the splat ( *
) operator (it also doesn't need to be patched into the Array
class). 在回答你的错误时,你编写的代码不需要splat(
*
)操作符(它也不需要修补到Array
类中)。 While patching into Array
and using self
allows you to call it like [1,2].second
, you could also write it as follows without patching into Array
: 虽然修补到
Array
并使用self
允许你像[1,2].second
那样调用它,但你也可以按如下方式编写它而无需修补Array
:
def second(arr)
arr.length <= 1 ? nil : arr[1]
end
Which would need to be called like second([1,2])
. 这需要被称为
second([1,2])
。
To find out more about the splat operator *
, try something like this explanation (I confess - the first Google result, but seems ok), but what it's doing in your example is turning your passed-in array into an array of an array - eg [1,2,3]
becomes [[1,2,3]]
. 要了解有关splat运算符
*
更多信息,请尝试类似这样的解释 (我承认 - 第一个Google结果,但似乎没问题),但它在您的示例中所做的是将传入的数组转换为数组的数组 -例如[1,2,3]
变为[[1,2,3]]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.