我又一次陷入了那种不舒服的境地,有人给我留下了一个我不知道的语言的代码片段,我必须维护它。虽然我还没有向自己介绍 Ruby,但它的某些部分非常简单,但我还是想听听您的解释。 开始了:
words = File.open("lengths.txt") {|f| f.read }.split # read all lines of a file in 'words'?
values = Array.new(0)
words.each { |value| values << value.to_i } # looked this one up, it's supposed to convert to an array of integers, right?
values.sort!
values.uniq!
diffs = Array.new(0) # this looks unused, unless I'm missing something obvious
sum = 0
s = 0 # another unused variable
# this looks like it's computing the sum of differences between successive
# elements, but that sum also remains unused, or does it?
values.each_index { |index| if index.to_i < values.length-1 then sum += values.at(index.to_i + 1) - values.at(index.to_i) end } # could you also explain the syntax here?
puts "delta has the value of\n"
# this will eventually print the minimum of the original values divided by 2
puts values.at(0) / 2
上面的脚本应该计算出列表中每两个连续元素(本质上是整数)之间的差异的平均值。我说这与它的实际作用相去甚远是对的,还是我错过了一些基本的东西,这可能是因为我没有 Ruby 知识?
最佳答案
解释 + 重构(删除未使用的变量,函数方法,each_cons
):
# Read integer numbers from file, sort them ASC and remove duplicates
values = File.read("lengths.txt").split.map(&:to_i).sort.uniq
# Take pairwise combinations and get the total sum of partial differences
partial_diffs = values.each_cons(2).map { |a, b| b - a }.inject(0, :+)
关于ruby - 解释 Ruby 代码片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4633620/