简体   繁体   English

找到数组的第二个元素

[英]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.

相关问题 二维数组第二元素上的Ruby插值搜索 - Ruby Interpolation Search on 2nd Element of a Two Dimensional Array 如何使用每个元素从第二个元素开始在数组中循环? - Ruby - How do I start cycling in an array from the 2nd element using each? - Ruby 如何从Ruby中的数组中获取第1,第2和第5个元素? - How to get the the 1st, 2nd and 5th element from an array in Ruby? 将“s”添加到数组中每个单词的末尾,除了给定数组中的第二个元素,只使用一行代码 - Add “s” to the end of each word in an array except for the 2nd element in the given array, only using one line of code Ruby:给出一个日期,找到下一个第二或第四个星期二 - Ruby: given a date find the next 2nd or 4th Tuesday 在Ruby中找到第二个最长的数组-Collat​​z猜想算法 - Finding the 2nd longest array in Ruby - Collatz conjecture algorithm 如何在Ruby中获取数组第二列的最大值和总和 - how to get max and sum of 2nd column of array in ruby Ruby:将散列数组的键/值对中的值替换为第二个数组中的值 - Ruby: replace the values in a key-value pair of an array of hashes with the values from a 2nd array 从哈希数组中的每个组中获取第二项的聪明方法? - Clever Way To Get 2nd Item From Each Group In Array Of Hashes? 找到数组元素 - find array element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM