While looking to solve a problem on I accidentally fell on a solution that was too condensed for me to understand (I am a Ruby beginner).
I have issues with a few lines, they should be easy but I come from C++ and am not used to 'easy'
The code opens a file and then splits the file into an array using commas as delimiters -- but what is this '%r' ?
What are we doing to the first and last element of the array? It looks like we're replacing them with, respectively, everything but the last element and everything but the first element .. ?
The hash is using a special for loop to create an alphabet hash..
And what is the last for loop doing? Creating a hash .. But I can't understand all that's happening..
Tao Te Ching Discussions : Chapter 9 (includes links to previous chapters)
What is the nature of conflict?
I have issues with a few lines, they should be easy but I come from C++ and am not used to 'easy'
Code:
file = File.open("names.txt")
array = file.gets.split(%r{","})
array[0] = array.first[1..array.first.strip.length-1]
array[array.length-1] = array.last[0..array.last.strip.length-2]
array.sort!
hash = Hash.new
("A".."Z").each_with_index{|i, index| hash[i] = index+1}
total = 0
array.each_with_index do |i, index|
total += (index+1) * i.strip.split(//).inject(0){ |sum,j| sum+hash[j]}
end
What are we doing to the first and last element of the array? It looks like we're replacing them with, respectively, everything but the last element and everything but the first element .. ?
The hash is using a special for loop to create an alphabet hash..
And what is the last for loop doing? Creating a hash .. But I can't understand all that's happening..
Tao Te Ching Discussions : Chapter 9 (includes links to previous chapters)
What is the nature of conflict?