Explaining a Ruby code snippet

Posted by Michael Foukarakis on Stack Overflow See other posts from Stack Overflow or by Michael Foukarakis
Published on 2011-01-08T11:23:52Z Indexed on 2011/01/08 19:54 UTC
Read the original article Hit count: 157

Filed under:

I'm in that uncomfortable position again, where somebody has left me with a code snippet in a language I don't know and I have to maintain it. While I haven't introduced Ruby to myself some parts of it are quite simple, but I'd like to hear your explanations nonetheless. Here goes:

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

The above script was supposed to figure out the average of the differences between every two successive elements (integers, essentially) in a list. Am I right in saying this is nowhere near what it actually does, or am I missing something fundamental, which is likely considering I have no Ruby knowledge?

© Stack Overflow or respective owner

Related posts about ruby