总结字串转变到其它与它相关的object的方法. 在这里整理分享一下, 希望能帮助到你.
变量相关
读取
instance_variable_get (" @name ") #返回@name值 设置
instance_variable_set (" @name ", " 三国演义 ") #@name = "三国演义"
method相关
string到method名 : send
book . send (" name ") #返回 book.name值 注意: book.send("name") = "三国演义" 会出错. 但可以:
book . send (" name= ", " 三国演义 ") #book.name = "三国演义"
单复数转化
string复数化 : pluralize 可用于生成table_name
" country ". pluralize #=> "countries"
string单数化 : singularize 和上面的相反
" posts ". singularize #=> "post"
table和class相关
将表格名转成class名: classify
" blog_pictures ". classify #=> "BlogPicture"
转成table_name(和上面的相反) : tableize
" BlogPicture ". tableize #=> "blog_pictures"
将class名转成class : constantize
" Country ". constantize #=> Country
可以将classify和constantize联用将string转成class model:
" books ". classify . constantize . find_by_name (" 三国演义 ") #=> Book.find_by_name("三国演义")