我正在使用ruby编写Google Sketchup中的插件,并且在尝试置换另一个数组中存在的数组中的不同元素时遇到了一个真正的问题,所有这些都取决于用户组合。
我有一个数组数组,如:
[["a, "b", c"], ["lol1", "lol2", lol3"], ["so1", "so2", "so3"]]
对于像这样的组合:
[1, 2, 3]
输出应该仍然相同:
[["a", "b", "c"], ["lol1", "lol2", "lol3"], ["so1", "so2", "so3"]]
但对于像这样的组合:
[2, 1, 3]
输出应为:
[["b", "a", "c"], ["lol2", "lol1", "lol3"], ["so2", "so1", "so3"]]
但对于像这样的组合:
[3, 2, 1]
输出应为:
[["c", "b", a"], ["lol3", "lol2", "lol1"], ["so3", "so2", "so1"]]
答案 0 :(得分:2)
ar = [["a, b, c"], ["lol1, lol2, lol3"], ["so1, so2, so3"]]
p maybe_this = ar.map{|sub_ar| sub_ar.first.split(', ')}
#[["a", "b", "c"], ["lol1", "lol2", "lol3"], ["so1", "so2", "so3"]]
idx = [2,1,3]
#indexing of an array is zero-based
p idx.map!{|i| i-1} #[1,0,2]
p res = maybe_this.map{|sub_ar| sub_ar.values_at(*idx)}
#[["b", "a", "c"], ["lol2", "lol1", "lol3"], ["so2", "so1", "so3"]]
短篇小说:values_at方法有多个参数; *idx
将数组splats为多个参数。
答案 1 :(得分:1)
也许你想要这个:
perm_idx = [1,2,3].permutation.to_a.index([2,3,1])
[["a", "b", "c"], ["lol1", "lol2", "lol3"], ["so1", "so2", "so3"]].map {|x| x.permutation.to_a[perm_idx] }
答案 2 :(得分:0)
不完全确定你想要什么,但这可能适合你:
a = [["a, b, c"], ["lol1, lol2, lol3"], ["so1, so2, so3"]]
def combi_with_join(ordering, arrays)
ordering = ordering.map {|x| x - 1}
arrays.map {|ar| [ar.first.split(/,\s*/).values_at(*ordering).join(", ")] }
end
puts combi_with_join([1, 2, 3], a).inspect
puts combi_with_join([2, 1, 3], a).inspect
puts combi_with_join([3, 2, 1], a).inspect
如果你真的想要一个数组数组......
def combi(ordering, arrays)
ordering = ordering.map {|x| x - 1}
arrays.map {|ar| ar.first.split(/,\s*/).values_at(*ordering) }
end
puts combi([1, 2, 3], a).inspect
puts combi([2, 1, 3], a).inspect
puts combi([3, 2, 1], a).inspect