如何将字符串转换为类方法? [英] How do I convert a string to a class method?

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

问题描述

这是如何在 Rails/Ruby 中将字符串转换为类:

This is how to convert a string to a class in Rails/Ruby:

p = "Post"
Kernel.const_get(p)
eval(p)
p.constantize

但是如果我从一个数组/活动记录对象中检索一个方法,比如:

But what if I am retrieving a method from an array/active record object like:

Post.description

但它可能是

Post.anything

其中任何东西都是像anything = "description"这样的字符串.

where anything is a string like anything = "description".

这很有帮助,因为我想重构一个非常大的类并减少代码行和重复.我怎样才能让它工作?

This is helpful since I want to refactor a very large class and reduce lines of code and repetition. How can I make it work?

推荐答案

Post.send(anything)

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

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