ruby - 数组元素之间的排列 [英] ruby - Permutation between elements of an array
问题描述
我正在使用 ruby 在 Google Sketchup 中编写一个插件,在尝试根据用户组合对数组中存在的两个数组进行置换时遇到了一个真正的问题.
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.
我有一个数组,如 [["1"],["lol"], ["so"]]
当我们有这样的组合时 <[1,2, 3]
没关系,它应该保持不变:[["1"],["lol"], ["so"]]
When we have a combination like this <[1,
2, 3]
it's fine, it should stay the same : [["1"],["lol"], ["so"]]
但是当我们有这样的组合 [2, 3, 1]
时,输出应该是: [["lol"], ["so"], ["1"]]
But when we have a combination like this [2, 3, 1]
, the output should be : [["lol"], ["so"], ["1"]]
对于 [3,1,2]
=> [["so"], ["1"], ["lol"]]
...等
编辑
对不起,我忘记了我有点像的数组:[["1, 2, 3"], ["lol1, lol2, lol3"], ["so1, so2, so3"]]
所以对于组合 [2, 3, 1]
的输出应该是: [["2, 3, 1"], ["lol2, lol3, lol1"], ["so2, so3, so1"]]
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"]]
谢谢你帮助我.
推荐答案
你可以使用 collect:
You could use collect:
array = [["1"],["lol"], ["so"]]
indexes = [2, 1, 3]
indexes.collect {|i| array[i-1]} #=> [["lol"], ["1"], ["so"]]
如果您将索引设置为基于 0,则可以删除 -1
If you set the indexes to be 0-based you could drop the -1
split 和 map 可用于将字符串转换为值:
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.
这篇关于ruby - 数组元素之间的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!