Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of first part of string in an array of strings

I have an array of strings from which I need to extract the first words, convert them to integers and get the their sum.

Example:

["5 Apple", "5 Orange", "15 Grapes"]

Expected output => 25

My attempt:

["5","5","15"].map(&:to_i).sum
like image 550
Robert Thomas Avatar asked Sep 17 '19 07:09

Robert Thomas


People also ask

How to find the sum of first n elements in an array?

Let’s see different ways to find the sum of first n elements. Initialize sum = 0. Iterate over the array up to nth element and add the current element to sum. Return sum. Create scanner class object. Ask use length of the array. Initialize the array with given size. Ask the user for array elements. Iterate over the array. Initialize sum = 0.

How to sum an array of elements in Python?

Ask use length of the array. Initialize the array with given size. Ask the user for array elements. Iterate over the array. Initialize sum = 0. Iterate over the array up to nth element and add the current element to sum.

What is the sum of string array elements in Java [duplicate]?

Sum of string array elements in java [duplicate] But the code int num = Integer.parseInt(element) gives NumberFormatException because Joe, Chandler, Rajat are not integers. So, how to resolve this problem. The answer should be the sum of 12+15+67=94.

What is an array of strings?

A string is a 1-D array of characters, so an array of strings is a 2-D array of characters.


Video Answer


2 Answers

I found the answer from your question.

["5 Apple", "5 Orange", "15 Grapes"].map(&:to_i).sum

In array if any integer convertable value is present then it will automatically convert into integer.

like image 155
Mayur Shah Avatar answered Oct 19 '22 07:10

Mayur Shah


Map with #split:

["5 Apple", "5 Orange", "15 Grapes"].map{|s| s.split.first.to_i }.sum
=> 25
like image 29
mrzasa Avatar answered Oct 19 '22 07:10

mrzasa