Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to store timestamps as keys in Hash and make it sortable?

I have a Comment model which the user can edit. I'd like to save every new version of the comment, much how it works in Facebook.

Instead of having an associated model where I create a new record for every new submitted edit, I was thinking to use Active Model's Serialization and insert a Hash key/value-pair for every new edit.

The submitted text would be the value and time of the edit would be the key.

Is it possible to save a DateTime value as a key and then be able to sort the Hash chronologically by the keys? And if positive, how would I create the keys?

like image 899
Fellow Stranger Avatar asked Nov 18 '25 16:11

Fellow Stranger


1 Answers

I agree with the comments about it being odd, but yes, it can be done in Ruby. You can set a Time object as the key to a hash like so:

hash = {}
hash[Time.now] = 'value'
hash
#=> {2015-09-30 11:45:41 -0500=>1}

If your time was initialized as a string, you can parse it into a Time object using:

Time.parse("12:00")
#=> 2015-09-30 12:00:00 -0500

Finally, hashes in Ruby maintain order since version 1.8 or 1.9, but are not sortable, so you can create an array of just the keys using Hash#keys and then sort the keys:

hash = {}
hash[Time.now] = 'value'
hash[Time.now] = 'value2'
hash[Time.now] = 'value3'
hash[Time.now] = 'value4'
hash[Time.now] = 'value5'
hash
#=> {
      2015-09-30 11:50:17 -0500=>"value",
      2015-09-30 11:50:18 -0500=>"value2",
      2015-09-30 12:04:05 -0500=>"value3",
      2015-09-30 12:04:04 -0500=>"value4",
      2015-09-30 12:04:06 -0500=>"value5",
    }

hash.keys
#=> [
      2015-09-30 11:50:17 -0500
      2015-09-30 11:50:18 -0500,
      2015-09-30 12:04:05 -0500,
      2015-09-30 12:04:04 -0500,
      2015-09-30 12:04:06 -0500,
    ]

shuffled_keys = hash.keys.shuffle
#=> [
      2015-09-30 12:04:04 -0500,
      2015-09-30 12:04:06 -0500,
      2015-09-30 11:50:18 -0500,
      2015-09-30 12:04:05 -0500,
      2015-09-30 11:50:17 -0500
    ]

latest_key = shuffled_keys.sort.last
#=> 2015-09-30 12:04:06 -0500

hash[latest_key]
#=> "value5"
like image 151
Travis Avatar answered Nov 21 '25 07:11

Travis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!