[英]How to get the the 1st, 2nd and 5th element from an array in Ruby?
How should I get the 1st, 2nd and 5th element from an array? 我应该如何从数组中获取第1,第2和第5个元素? Is there a very easy way to do it?
有一个很简单的方法吗?
这可以通过Array#values_at完成 :
p ['a','b','c','d','e'].values_at(0,1,4) #=> ["a", "b", "e"]
Pretty much the same as every other language. 与其他每种语言几乎相同。
irb(main):001:0> array = ['blue', 'red', 'green', 'orange', 'purple']
=> ["blue", "red", "green", "orange", "purple"]
irb(main):002:0> array[0]
=> "blue"
irb(main):003:0> array[1]
=> "red"
irb(main):004:0> array[4]
=> "purple"
Next time check the official documentation: http://www.ruby-doc.org/core-1.9.3/Array.html . 下次检查官方文档: http : //www.ruby-doc.org/core-1.9.3/Array.html 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.