2016-10-04 32 views
-1

我想在一个散列内存储一堆元素,但该键必须是当时的时间戳。我应该如何去做这样的事情?这是在纯粹的Ruby not Rails中。如何在Ruby中用键值存储历史记录(通过时间戳)?

+2

'store || = {}; store [Time.zone.now_to_i] ='some info'' –

+0

'Time#zone'返回一个'String'([link](http://ruby-doc.org/core-2.3.1/Time。 html#method-i-zone)),所以你不能将'now'应用到它。你可以做一个'Time.now.to_i',但这只会提供1秒的粒度。 OP需要指定他需要的时间戳的粒度。 – user1934428

+1

然后使用'Time.now.to_f'获得粒度 – Tiago

回答

2

这是做到这一点的一种方法:

class Store 
    def initialize() 
     @hash = {} 
    end 

    def add(data) 
     @hash[Time.now.to_f] = data 
    end 

    def to_s 
     @hash.to_s 
    end 

end 


new_store = Store.new 

new_store.add("foo"); 
new_store.add("bar"); 

puts new_store.to_s 

输出:

{1475565786.995899=>"foo", 1475565786.995907=>"bar"} 
1
hash = (Class.new(Hash) do 
    def << value 
    tap { |this| this[Time.now.strftime("%Y-%m-%d %H:%M:%S.%6N")] = value } 
    end 
end).new 
hash << :foo 
sleep 1 
hash << :bar << :baz 
hash 
#⇒ { 
# "2016-10-04 09:44:08.816475" => :foo, 
# "2016-10-04 09:44:09.824107" => :bar, 
# "2016-10-04 09:44:09.824125" => :baz 
# } 

NB:我downvoted的投入不遗余力的问题,而是回答了这个问题,因为该解决方案可能对未来的访问者有所帮助。

+0

非常好的解决方案。只是一个简单的问题:“自我[Time.now] =价值”比“self.tap”更糟? –

+0

@AndreyDeineko见'hash <<:bar <<:baz':连锁'<<'调用这个方法是返回'self'。 – mudasobwa

+0

绝对,没有想过这样 –

相关问题