Ruby发送(attribute.to_sym)Rails方法

我正在使用Ruby 1.9.2并且需要遍历表的所有值以确保所有内容都采用UTF-8编码。 有很多列,所以我希望能够使用column_names方法遍历所有列并将值编码为UTF-8。 我认为这可行:

def self.make_utf for listing in Listing.all for column in Listing.column_names column_value_utf = listing.send(column.to_sym).encode('UTF-8') listing.send(column.to_sym) = column_value_utf end listing.save end return "Updated columns to UTF-8" end 

但它返回一个错误:

 syntax error, unexpected '=', expecting keyword_end listing.send(column.to_sym) = column_value_utf 

我无法弄清楚如何使这项工作正常。

您正在使用send错误,并且您正在为您要执行的操作发送错误的符号:

 listing.send(column + '=', column_value_utf) 

你试图用column_value_utf作为参数调用x=方法(对于某些x ),这就是ox = column_value_utf通常会做的事情。 因此,您需要构建正确的方法名称(只需要一个字符串),然后将该方法的参数作为send参数send