【问题标题】:Ruby send(attribute.to_sym) for Rails MethodRails 方法的 Ruby 发送(attribute.to_sym)
【发布时间】:2011-09-19 04:06:10
【问题描述】:

我使用的是 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

我不知道如何使它正常工作。

【问题讨论】:

    标签: ruby ruby-on-rails-3


    【解决方案1】:

    您使用了错误的send,并且您发送的符号错误:

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

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

    【讨论】:

      猜你喜欢
      • 2011-11-15
      • 1970-01-01
      • 2010-09-19
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      相关资源
      最近更新 更多