这是示例:这只是简化版本,仅供您了解我在说什么。
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, ""]
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]] : '' }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句