如何在不使用eval的情况下将字符串转换为ruby / rails中的散列? [英] How to convert a string to a hash in ruby/rails without using eval?

查看:149
本文介绍了如何在不使用eval的情况下将字符串转换为ruby / rails中的散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是需要转换为散列字符串

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

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

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

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 的观点没有意义。它将以任一方式执行。

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.

h1 = {:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } }
# or 
h2 = eval("{:status => {:label => 'Status', :collection => return_misc_definitions('project_status') } }")

这两行之间没有功能上的区别,它们产生的结果完全相同。 / p>

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

h1 == h2 # => true

当然,如果可以的话,不要使用ruby散列的字符串表示。使用JSON或YAML。他们更安全(不要求 eval )。

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).

这篇关于如何在不使用eval的情况下将字符串转换为ruby / rails中的散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆