I am having trouble with the syntax for reduce. I have a hash of the following format:
H = {"Key1" => 1, "Key2" => 2}
I would like to use reduce to find the sum of the values in this function.
Something Like
H.reduce(0) {|memo, elem| memo+=elem}
I know this is wrong. I dont understand how I can make elem the value of the hash.
Reduce, or inject, is a useful method in any programming language but we 'll focus on ruby for now. Reduce is an enumerable method that can be used on hashes or arrays to reduce them into a single value or object. Say you wanted to get the sum of an array without the reduce method.
The 'reduce' method can be used to take an array and reduce it to a single value.
A hash table is a type of data structure that stores key-value pairs. The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.
Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.
You can make elem
contain the value by splitting it up in 2 variables:
H.reduce(0) {|memo, (key, val)| memo + val}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With