Rens
Rens

Reputation: 269

How do I find elements in array with another indexes array?

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

Answers (2)

Powers
Powers

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:

  1. The first block variable represents the days of the week ("mo", "tu", etc.) and is not used, but the convention is to name the variable "_"
  2. The 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

Arup Rakshit
Arup Rakshit

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

Related Questions