问题1
如何将类命名为字符串?
例如,假设Product
类有do_something
方法:
str = "product"
<what should be here based on str?>.do_something
问题2
如何在字段名称为字符串的情况下获取对象的字段?
例如,假设Product
类有price
字段:
str = "price"
product = Product.new
product.<what should be here based on str?> = 1200
答案 0 :(得分:5)
雅各布对第一个问题的回答假设您使用的是Rails并且如果您正常工作将会正常工作。如果您不是,您可以致电Kernel::const_get(str)
按名称查找现有常量。
send
是纯粹的红宝石。没有必要使用send
实习你的字符串(将它们转换为符号),直字符串工作正常。
答案 1 :(得分:4)
使用capitalize
和constantize
:
str.capitalize.constantize.do_something
使用send
:
product.send(str + '=', 1200)