user2071444
user2071444

Reputation:

How do I get elements of array by their indexes?

Is there any short possible way to have this executed:

var1 = %w{sub1 sub2 sub3 sub4 sub5}
var2 = [1,4]

I need to return the 1,4 values of var2 from var1. Now my output should be ["sub2", "sub5"]

Upvotes: 1

Views: 39

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

var1 = %w{sub1 sub2 sub3 sub4 sub5}
var2 = [1,4]

var1.values_at(*var2) # => ["sub2", "sub5"]

Upvotes: 4

Related Questions