Reputation: 269
I have two arrays:
["mo", "tu", "we", "th", "fr", "sa", "su"]
and [1, 5]
What is the shortest, most clean way to make a new array from the first array, based on the indexes of the second array? I would like to do something like this:
["mo", "tu", "we", "th", "fr", "sa", "su"][[1, 5]]
(not possible this way)
This would yield ["tu", "sa"]
.
How could this be done? Thanks in advance!
Upvotes: 2
Views: 96
Reputation: 19308
select
and with_index
can be chained to pluck certain elements from an array:
["mo", "tu", "we", "th", "fr", "sa", "su"].select.with_index {|_, index| [1, 5].include?(index)}
# => ["tu", "sa"]
Here's a couple of notes on this answer for Ruby newbies:
with_index
method can be chained with any of the awesome Ruby iterators to gain access to the index (similar to each_with_index
). In this case, there is no select_with_index
, so we use select.with_index
.Upvotes: 2
Reputation: 118261
Try this as below using Array#values_at
a = ["mo", "tu", "we", "th", "fr", "sa", "su"]
b= [1, 5]
c = a.values_at(*b)
# => ["tu", "sa"]
Upvotes: 5