Ruby on rails 按常量对哈希键排序
我有一张美国秩序表 我有不同的客户,他们的州有不同的标签 我正在抓取所有客户端及其状态,如下所示:Ruby on rails 按常量对哈希键排序,ruby-on-rails,hash,Ruby On Rails,Hash,我有一张美国秩序表 我有不同的客户,他们的州有不同的标签 我正在抓取所有客户端及其状态,如下所示: "client one" => {"shipped" => "state_zay", "ordered" => "state_bla"}, "client two" => {"shipped" => "state_bar", "ordered" => "state_foo"} ordered, shipped "client one" => {"ord
"client one" => {"shipped" => "state_zay", "ordered" => "state_bla"},
"client two" => {"shipped" => "state_bar", "ordered" => "state_foo"}
ordered, shipped
"client one" => {"ordered" => "state_bla", "shipped" => "state_zay"},
"client two" => {"ordered" => "state_foo", "shipped" => "state_bar"}
该常数将如下所示:
"client one" => {"shipped" => "state_zay", "ordered" => "state_bla"},
"client two" => {"shipped" => "state_bar", "ordered" => "state_foo"}
ordered, shipped
"client one" => {"ordered" => "state_bla", "shipped" => "state_zay"},
"client two" => {"ordered" => "state_foo", "shipped" => "state_bar"}
结果如下所示:
"client one" => {"shipped" => "state_zay", "ordered" => "state_bla"},
"client two" => {"shipped" => "state_bar", "ordered" => "state_foo"}
ordered, shipped
"client one" => {"ordered" => "state_bla", "shipped" => "state_zay"},
"client two" => {"ordered" => "state_foo", "shipped" => "state_bar"}
注意:我不希望它们按字母或数字排序
我想让一个参赛者代表正确的状态顺序,然后根据这个常数来排序键
你是如何做到这一点的?你可以通过这样做来实现你想要的产出
hash = {"client one"=>{"ordered"=>"state_bla", "shipped"=>"state_zay"},
"client two"=>{"ordered"=>"state_foo", "shipped"=>"state_bar"}}
hash.each do |key,value|
hash[key] = value.sort_by{|key,value| value}.to_h
end
puts hash # This will be the sorted hash
你能给出一个
常量的例子和你期望的结果吗?这可能会有帮助:它需要按数组排序,而不是按字母顺序排序。