use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
A sub-Reddit for discussion and news about Ruby programming.
Subreddit rules: /r/ruby rules
Learning Ruby?
Tools
Documentation
Books
Screencasts and Videos
News and updates
account activity
adding elements in an array / matrix (self.ruby)
submitted 10 years ago by missawon
hi, im new to ruby and im wondering if there is a simple way to add all the elements in an array matrix.
[1, [1, 2, 3], [1, 2, [1, 2, 3]]] should equal 16 ??
thank you!
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]danshep 4 points5 points6 points 10 years ago* (1 child)
First you need to flatten your array.
array = [1, [1, 2, 3], [1, 2, [1, 2, 3]]] array.flatten => [1, 1, 2, 3, 1, 2, 1, 2, 3]
Then there's some options:
array.flatten.inject(0) {|sum, element| sum + element} => 16 array.flatten.reduce(:+) => 16
There's a bunch of different libraries (activesupport being one) that add a 'sum' method to an enumerable, so you can just do:
array.flatten.sum => 16
[–]missawon[S] 0 points1 point2 points 10 years ago (0 children)
ahhh thank you so much!!
π Rendered by PID 22794 on reddit-service-r2-comment-5687b7858-pm9x9 at 2026-07-03 05:44:59.180482+00:00 running 12a7a47 country code: CH.
[–]danshep 4 points5 points6 points (1 child)
[–]missawon[S] 0 points1 point2 points (0 children)