Reputation: 6093
I am trying to learn Ruby, and I'm wondering how an array can be used to index another array, for example,
in Perl this is: my @x = @y[@ro]
, where all three variables are just generic arrays.
how can I accomplish the same thing in Ruby?
Upvotes: 1
Views: 66
Reputation: 434665
If I remember my Perl correctly, given:
my @ro = ('a', 'b', 'c', 'd', 'e');
my @y = (1, 3);
Then @ro[@y]
would be ('b', 'd')
so the notation is just a short form for extracting all the elements of the array @ro
at the indexes in @y
.
In Ruby, I'd use Array#values_at
and a splat thusly:
ro = %w[a b c d e]
y = [1, 3]
x = ro.values_at(*y)
The *y
splat unwraps the array and gives you its elements so ro.values_at(*y)
is equivalent to ro.values_at(1, 3)
in this case.
Upvotes: 5