Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails4散列访问值返回nil_Ruby On Rails_Ruby_Csv - Fatal编程技术网

Ruby on rails rails4散列访问值返回nil

Ruby on rails rails4散列访问值返回nil,ruby-on-rails,ruby,csv,Ruby On Rails,Ruby,Csv,我似乎被困在试图访问来自csv文件的哈希值的过程中,可能会用另一双眼睛指出我犯的明显错误。以下是相关代码: 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

我似乎被困在试图访问来自csv文件的哈希值的过程中,可能会用另一双眼睛指出我犯的明显错误。以下是相关代码:

  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}"
从日志文件中:(有效数据x'ed out或fake-注意studentid作为fixnum输入)

Rails 4.x Ruby 2.x操作系统Ubuntu
想法?

那些钥匙是符号。试一试

id    = data[:studentid] 
title = data[:title] 
注意:非
数据[':studentid']
':studentid'
只是一个以

开头的字符串,是ruby中的两种基本对象类型

以下哈希:

{:lastname=>"XXXX", :firstname=>"XXXXX", ...}
正在使用符号作为键,而不是字符串。要访问这些值,还必须使用符号:

lastname = data[:lastname]

再次重申:
:lastname
“:lastname”
不是同一件事;前者是一个符号,后者是一个字符串(以
开头)。

感谢Ursus,它现在可以工作了。我知道这很简单。再次感谢
lastname = data[:lastname]