[英]How to convert an array of string integers to an array of integers? Ruby
我有一個數組:
all_ages = ["11", "9", "10", "8", "9"]
我想把它轉換成一個整數數組,希望能更容易地將它們加在一起。 非常感謝任何幫助,尋找一級解決方案。
Enumerable#sum
可以用一個塊來調用,告訴 Ruby 如何對數組的元素求和,在這種情況下,首先在元素上調用String#to_i
。
all_ages = ["11", "9", "10", "8", "9"]
all_ages.sum(&:to_i)
#=> 47
all_ages = ["11", "9", "10", "8", "9"]
代碼
p all_ages.map(&:to_i).sum
或者
p all_ages.map { |x| x.to_i }.sum
Output
47
這是一種可能對添加到您的武器庫中有用的不同方法:
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
或者,如果您不想定義新方法:
total = 0
all_ages.each {|x| total += x.to_i}
total
#=> 47
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.