2

I seem to be stuck trying to access hash values coming from a csv file and could use a different pair of eyes to point out the obvious mistake I'm making. Here is the relevant code:

  CSV.foreach(filename, headers: true, header_converters: :symbol, converters: :all) do |row|
  data = row.to_hash
  id = data['studentid'] # (have also tried id = data[':studentid'] but there are no :'s in the csv file headers, and double quotes instead of single)
  title = data['title'] # also (title = data[:title'])
     logger.debug "data param: #{data.inspect}"
     logger.debug "data title param: #{title.inspect}"
     logger.debug "data studentid param: #{id.inspect}"

From the log file: (valid data x'ed out or fake - note studentid comes in as a fixnum)

data param: {:lastname=>"XXXX", :firstname=>"XXXXX", :title=>"XXXXXXX", :studentid=>123456, :date=>"XXXXXXXXXX"}
data title param: nil
data studentid param: nil

Rails 4.x Ruby 2.x OS Ubuntu Ideas?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367

2 Answers2

1

Those keys are symbols. Try

id    = data[:studentid] 
title = data[:title] 

Note: not data[':studentid']. ':studentid' is simply a string that starts with a :

Ursus
  • 29,643
  • 3
  • 33
  • 50
0

Symbols and Strings are two basic object types in ruby. They are different.

The following hash:

{:lastname=>"XXXX", :firstname=>"XXXXX", ...}

is using symbols as keys, not strings. In order to access the values, you must also use symbol:

lastname = data[:lastname]

Again, to reiterate: :lastname and ':lastname' are not the same thing; the former is a symbol, and the latter is a string (that starts with a :).

Community
  • 1
  • 1
Tom Lord
  • 27,404
  • 4
  • 50
  • 77