gpt4 book ai didi

ruby - 如何按值对哈希数组进行排序?

转载 作者:太空宇宙 更新时间:2023-11-03 17:12:06 25 4
gpt4 key购买 nike

我正在尝试根据给定的键值对哈希数组进行排序,并将首先返回数组顶部的该值,然后是剩余数据。

例子是:

students = [{name: "John Doe", age: 16, adviser: "Mrs. Robinson"},
{name: "John Smith", age: 18, adviser: "Mrs. Williams"},
{name: "Michael Rodriguez", age: 17, adviser: "Mr. Lee"}]

def sort_by_adviser(data, name)
...
end

> sort_by_adviser(students, "Mr. Lee")
=> [{name: "Michael Rodriguez", age: 17, adviser: "Mr. Lee"},
{name: "John Doe", age: 16, adviser: "Mrs. Robinson"},
{name: "John Smith", age: 18, adviser: "Mrs. Williams"}]

> sort_by_adviser(students, "Mrs. Williams")
=> [{name: "John Smith", age: 18, adviser: "Mrs. Williams"},
{name: "Michael Rodriguez", age: 17, adviser: "Mr. Lee"},
{name: "John Doe", age: 16, adviser: "Mrs. Robinson"}]

这里的输出将顾问的名字放在列表的顶部,然后是数组中的其他哈希值。

> sort_by_keyvalue(data, "Z")
=> [{letter: 'Z'},
{letter: 'A'},
.
.
.
{letter: 'Y'}]

> sort_by_keyvalue(data, 5)
=> [{number: 5, value: 'value1'},
{number: 5, value: 'value2'},
{number: 5, value: 'value3'},
{number: 9, value: 'value1'},
{number: 9, value: 'value2'},
{number: 8, value: 'value1'},
{number: 8, value: 'value2'},
{number: 7, value: 'value1'},
{number: 6, value: 'value1'},
{number: 4, value: 'value1'},
{number: 3, value: 'value1'},
{number: 2, value: 'value1'},
{number: 1, value: 'value1'},
{number: 1, value: 'value2'},
{number: 0, value: 'value1'}]

有人知道怎么做吗?

最佳答案

另一个实现:)

def sort_by_adviser(data, name)
data.each_with_index do |hash,index|
if hash[:adviser]==name
data.delete_at index #delete from array
data.unshift hash
break
end
end
data
end

> sort_by_adviser(students, "Mr. Lee")
#=> [{:name=>"Michael Rodriguez", :age=>17, :adviser=>"Mr. Lee"}, {:name=>"John Doe", :age=>16, :adviser=>"Mrs. Robinson"}, {:name=>"John Smith", :age=>18, :adviser=>"Mrs. Williams"}]

关于ruby - 如何按值对哈希数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11802065/

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