如何在不使用eval的情况下将字符串转换为ruby / rails中的哈希?
这是需要转换为hash
的string
。
"{:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } }"
我们不能使用eval
因为eval
将在字符串中执行return_misc_definitions('project_status')
方法。 是否有纯字符串操作来完成ruby / rails中的这种转换? 感谢帮助。
如前所述,您应该使用eval
。 关于eval
执行return_misc_definitions
没有意义。 它将以任何一种方式执行。
h1 = {:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } } # or h2 = eval("{:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } }")
这两条线之间没有function差异,它们产生完全相同的结果。
h1 == h2 # => true
当然,如果可以,请不要使用ruby哈希的字符串表示。 使用JSON或YAML。 它们更安全(不需要eval
)。