0

I'm coding a plugin in Google Sketchup with ruby and I faced a real problem while trying to permute two arrays that are present in an array all this depending on a user combination.

I have an array of arrays like [["1"],["lol"], ["so"]]

When we have a combination like this <[1, 2, 3] it's fine, it should stay the same : [["1"],["lol"], ["so"]]

But when we have a combination like this [2, 3, 1], the output should be : [["lol"], ["so"], ["1"]]

For [3,1,2] => [["so"], ["1"], ["lol"]]

...etc

EDIT
Sorry guys I forgot for the array I have a bit like : [["1, 2, 3"], ["lol1, lol2, lol3"], ["so1, so2, so3"]] so for the combination [2, 3, 1] the output should be : [["2, 3, 1"], ["lol2, lol3, lol1"], ["so2, so3, so1"]]

Thanks for helping me out.

1
  • A bit complicated; i've tried deleting the useless elements : delete_at() to have just the [["lol"]]. and then push the ["so"] and ["1"] but it didn't work for either with a.push or << or even array+array. Commented Feb 5, 2013 at 21:25

4 Answers 4

4

You could use collect:

array   = [["1"],["lol"], ["so"]]
indexes = [2, 1, 3]
indexes.collect {|i| array[i-1]} #=> [["lol"], ["1"], ["so"]]

If you set the indexes to be 0-based you could drop the -1

split and map can be used to turn your strings into values:

"1, 2, 3".split(",").map { |i| i.to_i} # [1, 2, 3]

You can then also split your strings

"lol2, lol3, lol1".split(/, /) #=> ["lol2", "lol3", "lol1"]

You should be able to put that together with the above to get what you want.

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

3 Comments

Arg, well, you got there first
I'm sorry, please see EDIT. Your code is working for '[["1"],["lol"], ["so"]]' array but not for the '[["1, 2, 3"], ["lol1, lol2, lol3"], ["so1, so2, so3"]]' array. Sorry for the changes.
@Paul Rubel It didn't work for me, since i'm dealing with a lot of arrays contained in an array like [["lol1, lol2, lol3"], ["lol4, lol5, lol6"], ["lol7, lol8, lol9"], ...]
1
indexes = [2, 1, 3]
array   = [["1"],["lol"], ["so"]]
result  = indexes.map{|index| array[index-1] }

1 Comment

I'm sorry, I forgot something, please see EDIT.
0

You should also take a look at active_enum

https://github.com/adzap/active_enum

You could do something like:

class YourClassName < ActiveEnum::Base
  value [1] => ['1']
  value [2] => ['lol'] 
  value [3] => ['so']
end

1 Comment

I'm sorry, please see EDIT.
0
a = [["1"], ["lol"], ["so"]]
index = [2, 1, 3]

index.collect {|i| a[i - 1]}

This outputs

[["lol"], ["1"], ["so"]]

1 Comment

I'm sorry, I forgot something, please see EDIT.

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.