问题
If I have an array a = [1,2,3,4,5,6,7,8,9,10]
and I want a subset of this array - the 1st, 5th and 7th elements. Is it possible to extract these from this array in a simple way. I was thinking something like:
a[0,4,6] = [1,5,7]
but that doesn't work.
Also is there a way to return all indices except those specified? For example, something like
a[-0,-4,-6] = [2,3,4,6,8,9,10]
回答1:
Here's one way:
[0,4,6].map{|i| a[i]}
回答2:
You can simply do:
[1] pry(main)> [1,2,3,4,5,6,7,8,9,10].values_at(0, 4, 6)
=> [1, 5, 7]
回答3:
a = [1,2,3,4,5,6,7,8,9,10]
For a[0,4,6] = [1,5,7] :
a.values_at(0, 4, 6)
=> [1, 5, 7]
For a[-0,-4,-6] = [2,3,4,6,8,9,10] :
a - a.values_at(0, 4, 6)
=> [2, 3, 4, 6, 8, 9, 10]
回答4:
In Ruby, Array objects have a method/operator []
which allows you to get/reference an object at a specific index, or a contiguous subset of objects specified by a range.
ary[index] → obj or nil
ary[start, length] → new_ary or nil
ary[range] → new_ary or nil
Personally, I like your syntax. It would be useful but it is not provided by the standard Array object. Until Ruby adopts your syntax, as others have suggested, you have the values_at
method to do exactly what you need.
values_at(selector,... ) → new_ary
If a = [1,2,3,4,5,6,7,8,9,10]
, then:
a.values_at(0, 4, 6)
=> [1, 5, 7]
来源:https://stackoverflow.com/questions/8921811/how-do-i-extract-specific-elements-from-an-array