Get index of value from an array?
I am not sure why I am struggling so much with this. Maybe because I am not overly familiar with Ruby?
I have a hash that I am passing to map() and I need to know my position while iterating inside map() (e.g. I am on X pass inside the map). It appears that I can retrieve the hash index, but not the position.
Okay, no big deal I guess. I extract the keys of my hash into a $hash_keys variable. Now inside of map() I want to search $hash_keys for a key and retrieve the array index (e.g. the position). Except now I don't see a function to search an array for a value and return its index.
What is the function I am looking for and why does it feel like I am going against the grain so much here?
Edit: I found a workaround
$hash_with_splay = $hash.reduce({}) |$return, $hash_item| {
$item_key = $hash_item[0]
$item_value = $hash_item[1]
$splay = Integer($return.length) / Integer(10)
$item_value_with_splay = $item_value + {'splay' => $splay }
$return + { $item_key => $item_value_with_splay }
}
Posted Feb 25, 2020, 6:05 PM UTC · edited
What’s the actual problem you’re trying to solve here?
I have a hiera hash with many Cron job configurations. I need to splay these Cron jobs to spread their load. I have a property to manually define splay, but I would like to add an algorithm that auto calculates splay if not provided. As an example, I would like to increment the Cron jobs splay by 1 minute for every 10 Cron jobs (100+ Cron jobs per server). To auto calculate this I am running the hash through map, which is where my question starts.
What about something like:
The slice function is interesting, but would really like to compute a hash where the splay value has been added. I would need to significantly restructure my code otherwise.
I found a workaround. I switched to using reduce() and I "rebuilding" the hash. In each iteration of reduce() I check the new hash's length and use that for calculating splay.
Cool cool. Here's a trick; indent each line of a code block and it displays as a block that's a bit more readable.
https://www.reddit.com/wiki/markdown#wiki_code_blocks_and_inline_code