Books / Ruby for Beginners / Chapter 30

Key presence in Hash

We often need to check if the key exists in a hash. It could be done without getting a value via “has_key?” method:

$ pry
> hh = { login: 'root', password: '123456' }
...
> hh.has_key?(:password)
true
>

has_key?” only checks for existence and doesn’t perform any value comparison. Example above is okay to use when you want to ensure that something is present.

Exercise Explain the difference between:

{
  "books": [
    {
      "id": 1,
      "name": "Tom Sawyer and Huckleberry Finn",
    },
    {
      "id": 2,
      "name": "Vingt mille lieues sous les mers",
    }
  ]
}

and

{
    "books": {
        "1": {
            "name": "Tom Sawyer and Huckleberry Finn"
        },
        "2": {
            "name": "Vingt mille lieues sous les mers"
        }
    }
}

Which data structure is better if we want to search for a book by id? Which data structure was designed to support constant O(1) search, and which one supports only linear O(N) search, and which one would you pick as a programmer? How many hashes and arrays were used in every example? How would you add a book to each of these data structures?


Licenses and Attributions


Speak Your Mind

-->