1

I have array a that holds the position of what the array b should.

a = [3, 2, 0, 1]
b = ["hello", "hi", 2332, "ben"]

I want to sort b so that it will become

["ben", 2332, "hello", "hi"]

where it get's its index from array a.

0

2 Answers 2

8

Have a look at Array#values_at

b = ["hello", "hi", 2332, "ben"]
a = [3, 2, 0, 1]

p b.values_at(*a)  # => ["ben", 2332, "hello", "hi"]
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, thank you! I was trying to do it using sort, index and map but it didn't work out for me. Thanks!
1

If you would like to use map here is how to:

b = ["hello", "hi", 2332, "ben"]
a = [3, 2, 0, 1]
a.map{|i| b[i]}  # => ["ben", 2332, "hello", "hi"]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.