ruby on rails - Possible to store timestamps as keys in Hash and make it sortable? -
i have comment model user can edit. i'd save every new version of comment, how works in facebook.
instead of having associated model create new record every new submitted edit, thinking use active model's serialization , insert hash key/value-pair every new edit.
the submitted text value , time of edit key.
is possible save datetime value key , able sort hash chronologically keys? , if positive, how create keys?
i agree comments being odd, yes, can done in ruby. can set time object key hash so:
hash = {} hash[time.now] = 'value' hash #=> {2015-09-30 11:45:41 -0500=>1}
if time initialized string, can parse 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, not sortable, can create array of keys using hash#keys
, sort 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"
Comments
Post a Comment