根据给定的索引重新排列数组

时间:2015-11-23 02:09:12

标签: arrays ruby

以下是这个例子: 这只是简化版本,只是为了让您了解我所说的内容。

current_properties = { "id" : 0, "name":1, "age": 2, "gender":3 }
new_index = { "id":0, "name":1, "gender": 2, "age": 3, "address":4 }

以下是数组值:

arr = ["1234", "John Doe", 35, "Male"]

有没有办法根据给定的索引交换值?那些不在当前属性上的索引必须插入一个空白元素。

所以这是预期的输出:

arr = ["1234", "John Doe", "Male", 35, ""]

2 个答案:

答案 0 :(得分:3)

current_properties = {"id" => 0, "name" => 1, "age" =>  2, "gender" => 3}
new_index = {"id" => 0, "name" => 1, "gender" => 2, "age" => 3, "address" => 4}
arr = ["1234", "John Doe", 35, "Male"]

idx = new_index.map {
  |key, value| [value, key]
}.sort.map {
  |value, key| current_properties[key]
}
# => [0, 1, 3, 2, nil]  => (A kind of mapping old -> new indexes)
new_arr = (0...new_index.length).map { |i| idx[i] ? arr[idx[i]] : '' }
# => ["1234", "John Doe", "Male", 35, ""]

更新:@CarySwoveland建议的更短版本,使用Enumerable#sort_by

...
idx = new_index.sort_by(&:last).map { |key, _| current_properties[key] }        
new_arr = (0...new_index.length).map { |i| idx[i] ? arr[idx[i]] : '' }

答案 1 :(得分:2)

假设我们可以将默认值添加到current_properties

current_properties.default = current_properties.size
(arr+[""]).values_at *new_index.sort_by(&:last).map {|k,_| current_properties[k]}
  #=> ["1234", "John Doe", "Male", 35, ""] 

步骤:

后:

current_properties.default = current_properties.size

对于任何非关键值:

current_properties["hurray!"]
  #=> 4

然后:

a = arr + [""]
  #=> => ["1234", "John Doe", 35, "Male", ""] 

b = new_index.sort_by(&:last)
  #=> [["id", 0], ["name", 1], ["gender", 2], ["age", 3], ["address", 4]] 

c = b.map { |k,_| current_properties[k] }
  #=> [0, 1, 3, 2, 4] 

a.values_at *c
  #=> ["1234", "John Doe", "Male", 35, ""]