2

I have two arrays. One Mapper and one with my ID's.

My Array with the external ID's:

genres_array = [12,28,16]

The Mapper Array (Internal-ID, External-ID)

mapper = [
   [1,12],
   [2,18],
   [3,19],
   [4,28],
   [5,16],
   [6,90],
]

As Result i would like to have now a new array, with only the internal values of the genres_array (the genres_array had the external values first). In this case the result would be [1,4,5]

I tried a lot of ways but i really have no idea how to solve this simple problem in a clean way. Im pretty sure it will be something like

genres_array.map { |genre_id| get_internal_id_from_mapper }

PS: It could also happen that a ID won't be found in the mapper. In that i case i just want to remove it from the array. Any idea?

0

3 Answers 3

1

You're looking for rassoc:

genres_array.map { |genre_id| mapper.rassoc(genre_id)[0] }

Which results in

[1, 4, 5]

EDIT: Just read the PS - try something like this:

genres_array.map { |genre_id|
    subarr = mapper.rassoc genre_id
    subarr[0] if subarr
}.compact

Then for an input of

genres_array = [12,28,100,16]

You would still get the output

[1, 4, 5]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you thats a very clean solution! Only one problem: If i have an id in my genres_array, that doesn't exists in the mapper array, i'm getting this exception: NoMethodError: undefined method []' for nil:NilClass`
1

Another way that won't throw an exception if the external id is not found:

genres_array = [12,28,16]

mapper = [
   [1,12],
   [2,18],
   [3,19],
   [4,28],
   [5,16],
   [6,90],
]

internal_ids = genres_array.map do |genre_id|
  element = mapper.detect { |m| m[1] == genre_id }
  element ? element[0] : nil
end.compact

Comments

1

Another solution involving a hash:

Hash[mapper].invert.values_at(*genres_array)

Asking for values that does not exist will return nil, if you do not want the nil just add .compact at the end.

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.