mirror of
https://github.com/jbranchaud/til
synced 2026-01-07 00:58:02 +00:00
Add a TIL on summing the values in collections.
This commit is contained in:
32
ruby/summing-collections.md
Normal file
32
ruby/summing-collections.md
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
# Summing Collections
|
||||||
|
|
||||||
|
Given a hash, `my_hash`,
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
my_hash = {
|
||||||
|
"one" => 1,
|
||||||
|
"two" => 2,
|
||||||
|
"three" => 5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
I want to determine the sum of the values in `my_hash`, which should be `8`.
|
||||||
|
|
||||||
|
This is similar to asking for the sum of the values in an array. In fact,
|
||||||
|
using `#values` on `my_hash` will leave us with the task of summing the
|
||||||
|
values in an array.
|
||||||
|
|
||||||
|
It turns out that to sum the values in an array, all you need is `#inject`
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
[1,2,5].inject(:+)
|
||||||
|
=> 8
|
||||||
|
```
|
||||||
|
|
||||||
|
So, if I want the sum of the values in a hash, such as `my_hash`, then all
|
||||||
|
that is needed is
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
my_hash.values.inject(:+)
|
||||||
|
=> 8
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user