Drew
Drew

Reputation: 13

Ruby: Confused about how to make sense of this code

I'm a little confused about one part of this code. In line 7 I have commented below.

01:states_file = File.open("states_abbrev.txt")
02:states = {}
03:while ! states_file.eof?
04:     first = states_file.gets.chomp
05:     #"ALABAMA,AL"
06:     data = first.split(",")
07:     states[ data[0] ] = data[1] #This line here.
08:end
09:puts states.inspect
10:
11:states_file.close

Line 5 is and example of what each line is like in the states_abbrev.txt file. Just a state, a comma, abbreviation, and a carriage return. All 50 states are in the file.

As you can see on line 7 the data[0] key seems to be overwritten by data[1]. So why is it when i run this code data[0] is still the key, and data[1] becomes the value?

Upvotes: 0

Views: 57

Answers (2)

spickermann
spickermann

Reputation: 107097

No, it is not the data[0] that is overwritten by data[1]. It is the hash states that is set data[1] (which is a state's name) for the key data[0] (which is the abbreviation part of the line).

Perhaps it is easier to understand when you introduce more variables or use better names:

file   = File.open("states_abbrev.txt")
states = {}

while !file.eof?
  line = file.gets.chomp
  name, abbr = line.split(",")
  states[abbr] = name
end

file.close

Btw: I would probably write something like this:

File.open('states_abbrev.txt') do |file|
  file.each_line.map { |line| line.chomp.split(',').reverse }.to_h
end

Upvotes: 1

sethi
sethi

Reputation: 1889

After line 6

data[0] is ALABAMA, data[1] is AL

After line 7

states is { 'ALABAMA' => 'AL' }

Its not overwriting data[0].. data[0] is the key and data[1] is the value.

One good thing you can try is ruby's irb

Upvotes: 1

Related Questions