1

I have an array:

all_ages = ["11", "9", "10", "8", "9"]

and I want to convert it to an array of integers to hopefully make it easier to add them all together. Any help greatly appreciated, looking for level one solutions.

2 Answers 2

7

Enumerable#sum can be called with a block telling Ruby how to sum the elements of the array, in this case, to call String#to_i on element first.

all_ages = ["11", "9", "10", "8", "9"]
all_ages.sum(&:to_i)
#=> 47
     
3
all_ages = ["11", "9", "10", "8", "9"]

Code

p all_ages.map(&:to_i).sum

Or

p all_ages.map { |x| x.to_i }.sum

Output

47
8
  • 1
    You legend. You have no idea how long I've spent on this. Thank you!
    – goatstash
    Commented Feb 12, 2022 at 8:50
  • how else could p all_ages.map(&:to_i).sum be written out?
    – goatstash
    Commented Feb 12, 2022 at 8:54
  • 4
    all_pages.sum(&:to_i) Commented Feb 12, 2022 at 9:06
  • 1
    I find the array.map {block} approach to be advantageous in that it also allows an easy way to replace x.to_i with Integer(x) if desired.
    – user16452228
    Commented Feb 12, 2022 at 20:18
  • 1
    @MichaelB: You mean like array.sum(&method(:Integer))? Commented Feb 13, 2022 at 17:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.