我有时会将键值对插入Hash
。
我如何构造这个哈希,以便我可以通过它们被创建的Time
对这些对进行排序?
如果我创建一个嵌套的Hash
,其中密钥将是一个时间戳(我认为是String
格式),而值 - 密钥对 - 将按时间顺序“轻松”排序还是有更好的方法吗?
答案 0 :(得分:2)
答案 1 :(得分:1)
每次向哈希值插入值时,只需将密钥设置为时间戳即可。
例如:
your_hash = {}
unique_timestamp = Time.now.to_s #time key as a string (you can create it each time
#you want to insert a value)
your_hash[unique_timestamp] = "new_value"
因此,你可以像“your_hash.inspect”那样检查你的哈希,你会看到你的密钥作为字符串时间戳格式,然后是你的值。