2

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!

2 Answers 2

5

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"]
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.