如何在不使用eval的情况下将字符串转换为ruby / rails中的哈希? [重复]

时间:2023-02-15 21:44:22

This question already has an answer here:

这个问题在这里已有答案:

Here is the string which needs to convert into a hash.

这是需要转换为哈希的字符串。

"{:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } }"

We can not use eval because eval will execute the method return_misc_definitions('project_status') in the string. Is there pure string operation to accomplish this conversion in ruby/rails? Thanks for help.

我们不能使用eval,因为eval将在字符串中执行return_misc_definitions('project_status')方法。是否有纯字符串操作来完成ruby / rails中的这种转换?感谢帮助。

1 个解决方案

#1


9  

As mentioned earlier, you should use eval. Your point about eval executing return_misc_definitions doesn't make sense. It will be executed either way.

如前所述,您应该使用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') } }")

There's no functional difference between these two lines, they produce exactly the same result.

这两条线之间没有功能差异,它们产生完全相同的结果。

h1 == h2 # => true

Of course, if you can, don't use string represenstation of ruby hashes. Use JSON or YAML. They're much safer (don't require eval).

当然,如果可以,请不要使用红宝石哈希的字符串表示。使用JSON或YAML。它们更安全(不需要评估)。

#1


9  

As mentioned earlier, you should use eval. Your point about eval executing return_misc_definitions doesn't make sense. It will be executed either way.

如前所述,您应该使用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') } }")

There's no functional difference between these two lines, they produce exactly the same result.

这两条线之间没有功能差异,它们产生完全相同的结果。

h1 == h2 # => true

Of course, if you can, don't use string represenstation of ruby hashes. Use JSON or YAML. They're much safer (don't require eval).

当然,如果可以,请不要使用红宝石哈希的字符串表示。使用JSON或YAML。它们更安全(不需要评估)。