Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

understanding code about arrays, hash, counting 1

Status
Not open for further replies.

Trevoke

Programmer
Jun 6, 2002
1,142
US
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' :)

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
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?
 
For starters:

%r is one way of saying 'this is a regular expression'. Other people would use different styles to declare the comma as a separator.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top