簡體   English   中英

如何根據內部哈希中的鍵值最有效地按順序遍歷哈希哈希?

[英]How can I most efficiently iterate over a hash of hashes in order based on key value in inner hash?

我有一個網站API返回的哈希值的JSON哈希值,我想根據內部哈希值中特定鍵的值來解析和顯示該哈希值。

我可以想到可以實現此目的的解決方案,但是它們會花費很多行代碼,而且效率似乎不高。 考慮到約定優於配置,肯定有一種方法可以在Rails中進行本地化。 我已經在Google上搜索了一下,但沒有發現任何涵蓋此問題的信息。

來自API的示例響應:

[{"banner":"01197271","birthday":"1991-01-11","committee_id":1,"created_at":"2012-08-08T01:56:02-05:00","email":"me@example.com","first_name":"Dan","graduation_date":"May 2013","hometown":"San Antonio","hours_enrolled":15,"id":2,"image":{"url":null,"thumb":{"url":null},"large":{"url":null}},"invitation_accepted_at":null,"invitation_limit":null,"invitation_sent_at":null,"invitation_token":null,"invited_by_id":null,"invited_by_type":null,"last_name":"Tester","local_apt":"","local_city":"San Antonio","local_state":"Texas","local_street":"One UTSA Circle","local_zip":"78249","major":"Computer Science","permanent_apt":"","permanent_city":"","permanent_state":"","permanent_street":"One UTSA Circle","permanent_zip":"","phone":"5558813284","same_address":true,"tour_trained":false,"updated_at":"2012-08-17T03:35:26-05:00","utsa_id":"uoi431"},
{"banner":"","birthday":"1990-10-25","committee_id":null,"created_at":"2012-08-03T16:19:23-05:00","email":"you@example.com","first_name":"Test","graduation_date":null,"hometown":null,"hours_enrolled":null,"id":1,"image":{"url":null,"thumb":{"url":null},"large":{"url":null}},"invitation_accepted_at":null,"invitation_limit":null,"invitation_sent_at":null,"invitation_token":null,"invited_by_id":null,"invited_by_type":null,"last_name":"User","local_apt":"","local_city":"","local_state":"","local_street":"","local_zip":"","major":null,"permanent_apt":"","permanent_city":"","permanent_state":"","permanent_street":"","permanent_zip":"","phone":"","same_address":false,"tour_trained":false,"updated_at":"2012-08-15T10:05:54-05:00","utsa_id":""}]

可能的解決方案是遍歷每個內部哈希,確定相關鍵值的值,然后根據鍵值與已測試哈希值相比的位置存儲。 完成后,返回。

好吧,如果您有一些對象被設置為可以解析此信息,則這些對象可以根據哈希參數建立自己。 所以你可以做這樣的事情

object = MyObject.create(your_hash_parameters)

其中your_hash_parameters是示例中顯示的參數。

我不確定如果參數多於您的對象知道該如何處理(如果它仍然可以自行構建),將會發生什么。 在這種情況下,可以使用delete_if方法排除不需要的屬性。

還有一點需要注意的是,如果這不是您想要保存到數據庫中的內容,並且僅用於顯示臨時信息。 我將使用attr_accessors設置一個模型,該模型代表您正在顯示的屬性。

如評論所述,我將創建一個ActiveResource對象並向其中添加相關方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM