Getting the values of a key in hashes if it is an array

● ARCHIVED · READ-ONLY
Started by Milena 5 posts View original ↗
  1. If I have a hash like this:

    RPGMakerWeb = { 1=> [1, 2, 3, 4, 5], 2=> [6, 7, 8, 9, 10]}How can I do the following?

    • Get a random value from RPGMakerWeb.keys[0]'s values.
    • Extract the values of keys[0] and so forth's value.

    I have tried my best to extract them but I just can't. Any help is appreciated.
  2. Random value

    Code:
    val = RPGMakerWeb[0][rand(RPGMakerWeb[0].size)]
  3. Alternative random value.

    RPGMakerWeb.keys.sample^this returns a random key value, eg. 1, 2, 3 or whatever the keys in your hash are called.

    To do similar to Theoallens suggestion above:

    RPGMakerWeb[ RPGMakerWeb.keys.sample ]

    Set value (searches for the corresponding key - ie, 1)

    RPGMakerWeb[1]^this returns the data stored within your hash[key]

    :)
  4. Dekita said:
    Alternative random value.

    RPGMakerWeb.keys.sample^this returns a random key value, eg. 1, 2, 3 or whatever the keys in your hash are called.
    To do similar to Theoallens suggestion above:

    RPGMakerWeb[ RPGMakerWeb.keys.sample ]
    How does this answer the question?
  5. I think Dekita was showing a more readable way to access a random value of an Enumerable object. For instance, to get a random value of any array stored in RPGMakerWeb, we simply

    Code:
    RPGMakerWeb[index].sample
    Dekita was probably just hinting on that method.