【问题标题】:ruby / rails: TypeError: can't convert Symbol into Integerruby / rails: TypeError: can't convert Symbol into Integer
【发布时间】:2015-04-01 11:37:31
【问题描述】:

我正在尝试更新我的 Representation 属性 ivpn 和 idirect(通过 rake 任务从 csv 文件,但我只是在这里打印程序的内容)并得到 TypeError:

# in Rails Console:
representation = Representation.where(id: 977)
# => Representation_id: 977, ivnp: false, idirect: false

rows = Hash.[:ivpn => "", :idirect => "x"] # originally rows are coming from csv-file

representation.update_attributes! ivpn: rows.any?{|r| r[:ivpn].present?}, idirect: rows.any? {|r| r[:idirect].present?}

TypeError: can't convert Symbol into Integer
        from (irb):42:in `[]'
        from (irb):42:in `block in irb_binding'
        from (irb):42:in `each'
        from (irb):42:in `any?'

我在这里缺少什么?

【问题讨论】:

  • 哈希声明中有字符串键 "ivpn" "idirect",但 any? 中的符号会阻止 :ivpn:idirect。始终如一。 rows 应该是一个哈希还是一个哈希数组?
  • 作为哈希,any? 可能会将r 中的每个键/值对转换为数组[key, value],并且该数组r 不能将:ivpn 符号作为键(仅限数字)
  • 有没有#any 的替代方法?
  • 可能,但我不完全理解rows 的结构是什么,或者您试图从中提取什么值到representation。你能从rows.inspect发一个样本吗?
  • 你不能在你的哈希上使用 select 方法从源中选择你需要/想要的所有键吗?

标签: ruby-on-rails ruby


【解决方案1】:

试试这个:

representation.update_attributes! ivpn: rows.any?[{|r| r[:ivpn].present?}], idirect: rows.any? [{|r| r[:idirect].present?}]

【讨论】:

  • 语法错误,意外'}',期待keyword_end;语法错误,意外的“|”,应为“}”
猜你喜欢
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多