将字符串转换为 ruby​​ 中的符号 [英] Convert string to symbol-able in ruby

查看:30
本文介绍了将字符串转换为 ruby​​ 中的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

符号通常是这样表示的

:book_author_title

但是如果我有一个字符串:

but if I have a string:

"Book Author Title"

rails/ruby 中是否有一种内置方法可以将其转换为一个符号,我可以在其中使用 : 表示法而无需执行原始字符串正则表达式替换?

is there a built in way in rails/ruby to convert it into a symbol where I can use the : notation without just doing a raw string regex replace?

推荐答案

Rails 获得了提供此类方法的 ActiveSupport::CoreExtensions::String::Inflections 模块.都值得一看.例如:

Rails got ActiveSupport::CoreExtensions::String::Inflections module that provides such methods. They're all worth looking at. For your example:

'Book Author Title'.parameterize.underscore.to_sym # :book_author_title

这篇关于将字符串转换为 ruby​​ 中的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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