1

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?

7
  • What do you mean by "Using one array to index another"? What are the semantics you want to achieve? Commented Sep 14, 2019 at 17:10
  • @JörgWMittag I showed in the code what I want to achieve. I can do this in perl and python, but I don't know how to accomplish my @x = @y[@ro] in Ruby Commented Sep 14, 2019 at 17:16
  • Your code doesn't show the semantics of what you want to achieve. What is @y? What is @ro? Can you show the definition of the my method? Commented Sep 14, 2019 at 17:18
  • @y @ro are generic arrays, my is just a declaration, I thought that this would be clear as this is simple Perl code. This is part of a larger project to translate rosettacode.org/wiki/P-value_correction#Perl into Ruby, which I'm using for tutorial purposes Commented Sep 14, 2019 at 17:21
  • What does the Perl code do? What is its result? What are its side-effects? What are the semantics of what you want to achieve? Can you provide a precise specification of what it is that you want to happen, including any and all rules, exceptions from those rules, corner cases, special cases, boundary cases, and edge cases? Can you provide sample inputs and outputs demonstrating what you expect to happen, both in normal cases, and in all the exceptions, corner cases, special cases, boundary cases, and edge cases? Commented Sep 14, 2019 at 17:44

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

...or y.map { |i| ro[i] }.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.