ruby - 解释 Ruby 代码片段

标签 ruby

我又一次陷入了那种不舒服的境地,有人给我留下了一个我不知道的语言的代码片段,我必须维护它。虽然我还没有向自己介绍 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/

相关文章:

mysql - Rails 未定义方法 `email' for nil :NilClass

ruby-on-rails - 有人请解释 rails 3 中表单的选择/选项

ruby-on-rails - Chef 和应用程序部署

ruby - 是否可以对nokogiri xml搜索方法进行 stub 处理?

ruby-on-rails - Netbeans/Ruby - 无关(?)自动完成信息

ruby - 如何通过不同的变量限制每个 `do` 循环

ruby - 在每个值都是数组的哈希中,如何使用数组项查找键?

css - 如何在 CSS 文件中从 Ruby 插入值

mysql - 如何在 Ubuntu 16.04 中通过 XAMPP 在 Rails 中使用 MySQL

ruby-on-rails - Rails 中的自动测试如何运行集成测试?