如何在不使用eval的情况下将字符串转换为ruby / rails中的散列?

编程入门 行业动态 更新时间:2024-10-27 18:33:24
本文介绍了如何在不使用eval的情况下将字符串转换为ruby / rails中的散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

我们不能使用 eval

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中的散列?

本文发布于:2023-10-25 22:31:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528304.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   情况下   如何在   rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!