开发者

NoMethodError for underscore

I want to convert the string

"Full Time"

to

"full_time"

When I using "Full Time".undersco开发者_JAVA百科re in irb, it prompt a error

NoMethodError: undefined method `underscore' for "Full Time":String

How can I fix it? Or is there any other way for me to get the above underscored result?


There is a rails helper method called underscore. If you fire your rails console (script/console) you will be able to use it:

"FullTime".gsub(/\s+/,'').underscore.to_sym
:full_time 

so what i think that you should do is, remove space and then apply the method described above. Note that I added to_sym just to show that it is possible as well, but if you don't need it, just remove it.

Note that it is a rails helper and not a ruby method from the String class. It will just works in the rails enviornment.


You could use gsub and replace all whitespaces to underscore

irb(main):008:0> "Full Time".downcase.gsub(/\s+/,"_")
=> "full_time"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜