[英]ruby - Permutation between elements of an array
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. 我正在用ruby在Google Sketchup中编码一个插件,而在尝试根据用户组合排列数组中存在的两个数组时,我遇到了一个实际问题。
I have an array of arrays like
[["1"],["lol"], ["so"]]
我有一个数组,如
[["1"],["lol"], ["so"]]
When we have a combination like this <
[1, 2, 3]
it's fine, it should stay the same :[["1"],["lol"], ["so"]]
当我们有这样的组合<
[1, 2, 3]
很好时,它应该保持不变:[["1"],["lol"], ["so"]]
But when we have a combination like this
[2, 3, 1]
, the output should be :[["lol"], ["so"], ["1"]]
但是当我们有这样的组合
[2, 3, 1]
,输出应该是:[["lol"], ["so"], ["1"]]
For
[3,1,2]
=>[["so"], ["1"], ["lol"]]
对于
[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"]]
对不起,我忘了数组了,我有点像:
[["1, 2, 3"], ["lol1, lol2, lol3"], ["so1, so2, so3"]]
所以对于组合[2, 3, 1]
输出应为: [["2, 3, 1"], ["lol2, lol3, lol1"], ["so2, so3, so1"]]
Thanks for helping me out. 谢谢你的协助。
You could use collect: 您可以使用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 如果将索引设置为基于0的索引,则可以删除-1
split and map can be used to turn your strings into values: split和map可用于将字符串转换为值:
"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. 您应该能够将其与以上内容结合起来以获得所需的内容。
indexes = [2, 1, 3]
array = [["1"],["lol"], ["so"]]
result = indexes.map{|index| array[index-1] }
You should also take a look at active_enum 您还应该看看active_enum
https://github.com/adzap/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
a = [["1"], ["lol"], ["so"]]
index = [2, 1, 3]
index.collect {|i| a[i - 1]}
This outputs 这个输出
[["lol"], ["1"], ["so"]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.