Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
How to convert an array of string integers to an array of integers? Ruby

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.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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
     
over 4 years ago · Santiago Trujillo Denunciar

0

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
over 4 years ago · Santiago Trujillo Denunciar

0

Here's a different approach that may be useful to add to your arsenal as well:

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

def sum_str_to_i (array)
  total = 0
  array.each {|x| total += x.to_i}
  total
end

sum_str_to_i(all_ages)
#=>  47

Or, if you don't want to define a new method:

total = 0
all_ages.each {|x| total += x.to_i}

total
#=>  47
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda