【问题标题】:trouble assigning value to nested hash给嵌套哈希赋值的麻烦
【发布时间】:2013-05-03 18:30:19
【问题描述】:

我有一个嵌套散列,我想为其赋值,但 ruby​​ 一直抱怨它。

哈希:

 data = {
    name: contact.xpath('./span[1]').text.delete("\r\n").strip,
    email: contact.xpath('./a').text,
    offices: [
        postal: contact.text.split("\r\n")[4].strip, 
        tel: /(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})/.match(contact).to_s     
    ],
    url: url
 }

我的任务

data[:offices][:postal] = ""

错误:

Line 42 - data[:offices][:postal] = "" -- in `[]='
#<TypeError: can't convert Symbol into Integer>

我尝试了一些其他语法,但无济于事。任何帮助表示赞赏:)

【问题讨论】:

  • 在此处显示您的数据哈希。

标签: ruby hash variable-assignment


【解决方案1】:
offices: [
        postal: contact.text.split("\r\n")[4].strip, 
        tel: /(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})/.match(contact).to_s     
    ],

这不是嵌套哈希。使用花括号:

offices: {
        postal: contact.text.split("\r\n")[4].strip, 
        tel: /(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})/.match(contact).to_s     
    },

【讨论】:

  • 阅读文档。 (大括号)用于散列,(方)括号用于数组。没有“方括号”之类的东西。
  • 不管怎样,如果你使用方括号,Ruby 会自动插入花括号,所以你最终会得到一个包含单个哈希的单值数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
相关资源
最近更新 更多