排序对象的哈希表(由对象的属性)在红宝石 [英] Sorting a hash table of objects (by the attributes of the objects) in Ruby

查看:159
本文介绍了排序对象的哈希表(由对象的属性)在红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个叫做Person类,它包含的东西,如姓氏,名字,地址等。

Say I have a class called Person, and it contains things such as last name, first name, address, etc.

我也有一个需要由姓和名排序Person对象的哈希表。
据我所知,sort_by不会永久地改变了哈希,这是很好的,我只需要按照这个顺序进行打印。目前,我试图理清/打印的地方使用:

I also have a hash table of Person objects that needs to be sorted by last and first name. I understand that a sort_by will not change the hash permanently, which is fine, I only need to print in that order. Currently, I am trying to sort/print in place using:

@hash.sort_by {|a,b| a <=> b}.each { |person| puts person.last}

我已经超载的&lt; =>操作员通过最后/先进行排序,但没有出现真正的排序。看跌期权存在只是输出哈希的原始顺序。我花了好4.天尝试算出这个(它是一所学校的分配,我的第一个Ruby程序)。有任何想法吗?我相信这是很容易,但我有困难的时候把我的大脑进行思维的C ++的方式。

I have overloaded the <=> operator to sort by last/first, but nothing appears to actually sort. The puts there simply outputs in the hash's original order. I have spent a good 4 days trying to figure this out (it is a school assignment, and my first Ruby program). Any ideas? I am sure this is easy, but I am having the hardest time bringing my brain out of the C++ way of thinking.

推荐答案

您似乎混淆排序 sort_by

排序从收集到块产生两个对象,并希望你返回&LT; =>像值:-1,0或1取决于是否参数是平等的,升序或降序,例如:

sort yields two objects from the collection to the block and expects you to return a <=> like value: -1,0 or 1 depending on whether the arguments are equal, ascending or descending, for example

%w(one two three four five).sort {|a,b| a.length <=> b.length}

排序按长度字符串。这是形式的,如果你想用你的&LT使用; =>运营商

Sorts the strings by length. This is the form to use if you want to use your <=> operator

sort_by 在一个时间产生从集合一个对象,并希望你回到你想要的东西进行排序 - 你不应该在这里做任何比较。红宝石然后使用&LT; =>对这些objecfs排序您的收藏。在previous例如可以通过电子邮件改写为

sort_by yields one object from the collection at a time and expects you to return what you want to sort by - you shouldn't be doing any comparison here. Ruby then uses <=> on these objecfs to sort your collection. The previous example can e rewritten as

%w(one two three four five).sort_by {|s| s.length}

此也被称为一个的Schwartzian变换

在你的情况的收集是一个哈希这样的事情会稍微复杂:被传递到块的值是包含键/值对数组,所以你需要从对提取人的对象。你也可以只对@ hash.keys或@ hash.values​​(取决于人的对象是否键或值)工作

In your case the collection is a hash so things are slightly more complicated: the values that are passed into the block are arrays that contain key/value pairs, so you'll need to extract the person object from that pair. You could also just work on @hash.keys or @hash.values (depending on whether the person objects are keys or values)

这篇关于排序对象的哈希表(由对象的属性)在红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆