Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce Hash Values

Tags:

ruby

hash

reduce

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.

like image 494
richsoni Avatar asked Dec 14 '12 16:12

richsoni


People also ask

Can you reduce a hash Ruby?

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.

What does reduce do in Ruby?

The 'reduce' method can be used to take an array and reduce it to a single value.

What is a key value hash?

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.

How do you add to a hash?

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.


1 Answers

You can make elem contain the value by splitting it up in 2 variables:

H.reduce(0) {|memo, (key, val)| memo + val} 
like image 91
steenslag Avatar answered Sep 25 '22 19:09

steenslag