Vic*_*Lam 1 ruby ruby-on-rails
我想转换字符串
"Full Time"
Run Code Online (Sandbox Code Playgroud)
至
"full_time"
Run Code Online (Sandbox Code Playgroud)
当我在irb中使用"Full Time".underscore时,它会提示错误
NoMethodError: undefined method `underscore' for "Full Time":String
Run Code Online (Sandbox Code Playgroud)
我该如何解决?或者还有其他方法可以让我获得上述强调结果吗?
有一个名为下划线的rails helper方法.如果您启动rails控制台(脚本/控制台),您将能够使用它:
"FullTime".gsub(/\s+/,'').underscore.to_sym
:full_time
Run Code Online (Sandbox Code Playgroud)
所以我认为你应该做的是,删除空格,然后应用上述方法.请注意,我添加to_sym只是为了表明它也是可能的,但如果你不需要它,只需删除它.
请注意,它是一个rails助手,而不是String类中的ruby方法.它只适用于rails环境.