我想在Ruby的数组中返回总和最高的字符串

时间:2015-05-13 00:48:29

标签: arrays ruby

到目前为止,我能够返回字符串的总和:

puts "Please enter strings of #'s to find the number that has the greatest sum."
puts "Use commas to separate #'s."
user_input = gets.chomp
array = user_input.split(",")
array.map do |num_string|
  num_string.chars.map(&:to_i).inject(:+)
end

但我希望返回加起来最高值的字符串。例如:如果我有数组= [" 123"," 324"," 644"]我需要它来返回每个值的总和,所以结果应该是分别为6,9和14。因为1 + 2 + 3 = 6等我这么远,但现在我需要返回" 644"作为答案,因为它是总和为最高值的字符串。

2 个答案:

答案 0 :(得分:3)

我建议您使用Enumerable#max_by

arr = ["123","324","644"]

arr.max_by { |s| s.each_char.reduce(0) { |t,c| t+c.to_i } }
  #=> "644"

让我们看看它是如何工作的。 Enumerable#max_by计算arr的每个元素的值,并返回计算值最大的arr元素。每个元素的值的计算由max_by块完成。

enum0 = arr.max_by
  #=> #<Enumerator: ["123", "324", "644"]:max_by> 

您可以看到此枚举器的三个元素。有时它不是那么明显,但你总是可以通过将枚举器转换为数组来看到它们是什么:

enum0.to_a
  #=> ["123", "324", "644"]

enum0的元素通过方法Enumerator#each(后者调用Array#each)传递给块。你会发现:

enum0.each { |s| s.each_char.reduce(0) { |t,c| t+c.to_i } }

返回"644"

枚举器的第一个元素("123")由each传递给块,并分配给块变量s。我们可以使用方法Enumerator#next来模拟它:

s = enum0.next
  #=> "123"

在这个区块内我们有另一个枚举器:

enum1 = s.each_char
  #=> #<Enumerator: "123":each_char> 
enum1.to_a
  #=> ["1", "2", "3"]
enum1.reduce(0) { |t,c| t+c.to_i }
  #=> 6

最后一句话相当于:

0            #  initial value of t
0 + "1".to_i #=> 1 (new value of t)
1 + "2".to_i #=> 3 (new value of t)
3 + "3".to_i #=> 6 (new value of t)
然后6返回

reduce

对于enum0的下一个元素:

s = enum0.next
  #=> "324"
s.each_char.reduce(0) { |t,c| t+c.to_i }
  #=> 9

以及最后一个元素enum0

s = enum0.next
  #=> "644"
s.each_char.reduce(0) { |t,c| t+c.to_i }
  #=> 14

由于14[6, 9, 14]中的最大整数,max_by会返回arr的最后一个元素,"644"

答案 1 :(得分:2)

yourArray = ["123","324","644"]
highest = -1
pos = -1
yourArray.each_with_index{ |str, i| 
  sum = str.split("").map(&:to_i).reduce(:+)
  highest = [highest,sum].max
  pos = i if highest == sum
}
puts "highest value is " + yourArray[pos]

让我们看看每一步,map让我们枚举数组并返回一个新的数组,包含我们从map返回的内容:

yourArray.map{ |str| ... }

在这里,我们将数组中的字符串转换为[&#34; 1&#34;,&#34; 2&#34;,&#34; 3&#34;]的数组例如,to_i部分将此转换为数组,如[1,2,3],然后最终reduce减去我们的总和:

sum = str.split("").map(&:to_i).reduce(:+)

在这里,我们一直在追踪到目前为止我们所看到的最高金额的循环:

highest = [highest,sum].max

如果当前总和最高,则将其位置存储在数组中

pos = i if highest = sum

最后,使用存储的数组位置打印出原始数组中存在的任何内容(位置对齐):

puts "highest value is " + yourArray[pos]