简体   繁体   English

Ruby:如何从数组内部的整数中删除特定数字?

[英]Ruby: How to remove specific digits from integers that are inside an array?

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. 我想采用一个整数数组,例如[155, 151, 2, 15]并删除一个特定的数字(在本例中为5),然后添加新的数字。 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: 也许您可以使用map来代替每个,这样就避免了将块内变换的每个元素推入新的初始化数组,例如:

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). 如果使用ruby 2.4或更高版本,则可以使用Enumerable#sum代替reduce(这似乎是一个更快的选择)。

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

eval(arr.join('+').delete('5'))    
#=> 15

using inject : 使用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. 使用eval的解决方案更有趣,但是使用inject的解决方案可以说更容易理解。 Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM