简体   繁体   English

如何从Ruby中的数组中获取第1,第2和第5个元素?

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

相关问题 Ruby DateTime格式:如何获得1st,2nd,3rd,4th? - Ruby DateTime format: How can I get 1st, 2nd, 3rd, 4th? Ruby DateTime格式:无法获得1st,5th等 - Ruby DateTime format: Unable to get 1st, 5th etc 如何在日期旁边添加字符“ st”,“ nd”,“ th”,例如1st,2nd,28th - How to add the characters “st” ,“nd”, “th” next to the day e.g 1st, 2nd, 28th 对于序数的Ruby格式:'1'为'1st','2'为'2nd'等 - Ruby formatting for ordinals: '1' as '1st', '2' as '2nd' etc 如何确保在独立脚本中安装ruby gem-第一次运行失败,第二次运行有效 - How to ensure ruby gem install in a standalone script - 1st run fails, 2nd run works 如何制作字符串第一字母大写,第二字母无大写,第三字母大写,第四字母无大写…? - How to make a string 1st letter caps, 2nd letter noncaps, 3rd letter caps, 4th letter noncaps…? 如何使用每个元素从第二个元素开始在数组中循环? - Ruby - How do I start cycling in an array from the 2nd element using each? - Ruby 如何在Ruby中获取数组第二列的最大值和总和 - how to get max and sum of 2nd column of array in ruby 二维数组第二元素上的Ruby插值搜索 - Ruby Interpolation Search on 2nd Element of a Two Dimensional Array 找到数组的第二个元素 - Find the 2nd element of array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM