在显式转换为字符串时获得“没有将String隐式转换为整数”错误

时间:2014-08-06 05:27:57

标签: ruby-on-rails ruby-on-rails-4

我收到了一个令人惊讶的错误。我检查一个记录的ID是否与另一个对象的ID匹配:

new_post = posts_with_score.detect {|post| post["id"].to_s == original_post.id.to_s }

我收到错误TypeError (no implicit conversion of String into Integer)。这是令人惊讶的,因为id 显式转换为字符串

我在这里看不到什么?为什么这个等式检查试图转换为整数?

编辑:

以下是检测内部post的内容:{"time_since_post_in_hours"=>15.810972532939815, "upvote_count"=>324, "id"=>1, "score"=>4.3103601541380465}

1 个答案:

答案 0 :(得分:0)

由于哈希的结构方式,当你遍历它时,post是一个数组。因此,当您发布[" id"] Ruby尝试将您的索引(字符串)转换为整数。当你收到错误时就是这样。请注意,错误是"没有将 String隐式转换为Integer "而不是相反。因此,请检查哈希结构以根据需要进行调整。