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)
I found the answer from your question.
["5 Apple", "5 Orange", "15 Grapes"].map(&:to_i).sum
Run Code Online (Sandbox Code Playgroud)
在数组中,如果存在任何可转换的整数值,则它将自动转换为整数。
Map with #split:
["5 Apple", "5 Orange", "15 Grapes"].map{|s| s.split.first.to_i }.sum
=> 25
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |