Ruby send(attribute.to_sym) 用于 Rails 方法 [英] Ruby send(attribute.to_sym) for Rails Method
问题描述
我使用的是 Ruby 1.9.2,需要检查表的所有值以确保所有内容都采用 UTF-8 编码.有很多列,所以我希望能够使用 column_names 方法遍历所有列并将值编码为 UTF-8.我认为这可能有效:
I'm using Ruby 1.9.2 and need to go through all of the values for a table to make sure everything is in UTF-8 encoding. There are a lot of columns so I was hoping to be able to use the column_names method to loop through them all and encode the values to UTF-8. I thought this might work:
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
我不知道如何使其正常工作.
I can't figure out how to make this work correctly.
推荐答案
您正在使用 send
错误,并且您发送了错误的符号来表示您想要执行的操作:
You're using send
wrong and you're sending the wrong symbol for what you want to do:
listing.send(column + '=', column_value_utf)
您正在尝试使用 column_value_utf
作为参数调用 x=
方法(对于某些 x
),这就是 ox = column_value_utf
通常会这样做.因此,您需要构建正确的方法名称(只需一个字符串即可),然后将该方法的参数作为参数发送到 send
.
You're trying to call the x=
method (for some x
) with column_value_utf
as an argument, that's what o.x = column_value_utf
would normally do. So you need to build the right method name (just a string will do) and then send the arguments for that method in as arguments to send
.
这篇关于Ruby send(attribute.to_sym) 用于 Rails 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!