I'm new to programming. I would like to take an array of Integers, like [155, 151, 2, 15]
and remove a specific digit, in this case 5, and add up the new numbers. I've broken this problem up into smaller steps, and gotten the result I wanted. I'm just wondering if there are easier ways to do a problem like this? Maybe a different method I could use? Any help is greatly appreciated.
Here is the code I have:
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(:+)
Maybe you can use map
instead each, this way you avoid having to push to a new initialized array each element transformed inside the block, like:
p [155, 151, 2, 15].map { |el| el.to_s.delete('5').to_i }.reduce(:+)
# 15
If using ruby 2.4 or higher you can use Enumerable#sum
instead reduce (which seems to be a faster option).
p [155, 151, 2, 15].sum { |el| el.to_s.delete('5').to_i }
# 15
arr = [155, 151, 2, 15]
arr.sum { |n| (n.digits - [5]).reverse.join.to_i }
#=> 15
using eval
:
eval(arr.join('+').delete('5'))
#=> 15
using inject
:
arr.inject(0){|sum, element| element.to_s.delete('5').to_i + sum }
#=> 15
The solution using eval
is more fun, but the solution using inject
is arguably easier to understand. Cheers.
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.