gpt4 book ai didi

arrays - 如何根据 Ruby 中另一个数组的值对散列进行排序?

转载 作者:行者123 更新时间:2023-12-05 02:58:00 25 4
gpt4 key购买 nike

看起来小菜一碟,但是解决不了..

elements = ['one', 'two', 'three']

sort_me = {'three': 3, 'two': 2, 'one': 1}

sort_me.sort_by { |k, _| elements.index k }.to_h 没有按照应有的方式对其进行排序。哈希值保持不变。

所需的输出是 {:one=>1, :two=>2, :three=>3}

最佳答案

您不需要对任何内容进行排序,也不需要创建查找表。您的数组已经按照您想要的方式排序,并且您的 sort_me 散列已经是一个查找表:

elements = ['one', 'two', 'three']
# => ["one", "two", "three"]
sort_me = {'three' => 3, 'two' => 2, 'one' => 1}
# => {"three"=>3, "two"=>2, "one"=>1}
elements.map{|key| [key, sort_me[key] ] }.to_h
# => {"one"=>1, "two"=>2, "three"=>3}

如果你想使用符号和字符串:

elements = ['one', 'two', 'three']
# => ["one", "two", "three"]
sort_me = {three: 3, two: 2, one: 1}
# => {:three=>3, :two=>2, :one=>1}
elements.map{|key| [key.to_sym, sort_me[key.to_sym] ] }.to_h
# => {:one=>1, :two=>2, :three=>3}

最后,如果散列中没有使用某些元素,您可以简单地删除具有nil 值的对:

elements = ['one', 'two', 'two_and_a_half', 'three']
# => ["one", "two", "two_and_a_half", "three"]
elements.map{|key| [key.to_sym, sort_me[key.to_sym] ] }.to_h
# => {:one=>1, :two=>2, :two_and_a_half=>nil, :three=>3}
elements.map{|key| [key.to_sym, sort_me[key.to_sym] ] }.reject{|k, v| v.nil? }.to_h
# => {:one=>1, :two=>2, :three=>3}

关于arrays - 如何根据 Ruby 中另一个数组的值对散列进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59429405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com