【发布时间】:2018-06-29 19:38:11
【问题描述】:
我是编程新手。我想取一个整数数组,比如[155, 151, 2, 15] 并删除一个特定数字,在本例中为 5,然后将新数字相加。我已经把这个问题分解成更小的步骤,并得到了我想要的结果。我只是想知道是否有更简单的方法来解决这样的问题?也许我可以使用不同的方法?非常感谢任何帮助。
这是我的代码:
arr = [155, 151, 2, 15]
# goal: remove the 5 digit from values and add
# new numbers together --> 1 + 11 + 2 + 1 == 15
# convert to arr of strings and delete zeros
str_arr = []
arr.each do |el|
str_arr << el.to_s.delete('5')
end
# convert to arr of nums
num_arr = []
str_arr.each do |el|
num_arr << el.to_i
end
# reduce num_arr
num_arr.reduce(:+)
【问题讨论】:
-
不是将元素推送到外部数组,而是使用
map返回一个映射值数组。例如,您的第一个示例arr.map { |e| e.to_s.delete('5') } -
require 'json'; JSON.parse([155, 151, 2, 15].to_json.delete('5')).sum #=> 15怎么样?
标签: arrays ruby type-conversion enumerable