Home>

I want to delete the very first key and value of the hash.

I get some data with the API and add it to the hash.

Data is skipped from time to time, so if the number of hashes exceeds 1000, I want to delete the first key and value. (I want to limit the number stored in the hash by the first-in first-out method)

If this is an array rather than a hash, after adding data to the array (referred to as db),
With the instruction to delete the 1000th from the back, you can prevent the array from entering more than 1000.

loop {
 db<<data
 db.delete_at (-1000)
}

I want to do the same with hashing.
It would be helpful if you could give me some sample code.

  • Answer # 1

    Theshiftmethod removes the beginning of either an array or hash.
    The purpose of the method is "retrieve".

    For

    arrays, there is a reverseunshiftandpoppushfor the end.

  • Answer # 2

    Reference Information

    Is the order of keys returned by Ruby Hash # key undefined?
    http://igrc.hatenablog.com/entry/2018/01/16/014814

      

    ...
      Hash # shift =>Remove the first element in the order in which the keys were added and return it as an array [key, value].
      ...

    Ruby API reference Hash
    https://docs.ruby-lang.org/en/latest/class/Hash.html#I_SHIFT