Sum of first part of string in an array of strings

Rob*_*mas 5 ruby arrays string

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"]
Run Code Online (Sandbox Code Playgroud)

Expected output => 25

My attempt:

["5","5","15"].map(&:to_i).sum
Run Code Online (Sandbox Code Playgroud)

May*_*hah 8

I found the answer from your question.

["5 Apple", "5 Orange", "15 Grapes"].map(&:to_i).sum
Run Code Online (Sandbox Code Playgroud)

在数组中,如果存在任何可转换的整数值,则它将自动转换为整数。


mrz*_*asa 5

Map with #split:

["5 Apple", "5 Orange", "15 Grapes"].map{|s| s.split.first.to_i }.sum
=> 25
Run Code Online (Sandbox Code Playgroud)