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
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.
Map with #split
:
["5 Apple", "5 Orange", "15 Grapes"].map{|s| s.split.first.to_i }.sum
=> 25
String#to_i
looks for digits at the start of the string and converts them to integers:
'Foo'.to_i # => 0
'5 Bar'.to_i # => 5
'Baz 5'.to_i # => 0
Hence just sum the result of to_i
:
["5 Apple", "5 Orange", "15 Grapes"].sum(&:to_i) # => 25
["5 Apple", "5 Orange", "15 Grapes"].sum { |w| w.split(' ').first.to_i }
会做到的。
I see this is now the most popular question in the Ruby section, so here's another way:
["5 Apple", "5 Orange", "15 Grapes"].reduce(0) {|sum,n| sum + n.to_i}
Or as suggested by @EricDuminil, just:
["5 Apple", "5 Orange", "15 Grapes"].sum(&:to_i)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.