问题描述:

I'm using create() to insert into a table that already exists, but some of the table fields and variable names start with a number. Currently in Ruby I'm getting a syntax error "unexpected tIDENTIFIER" when I try to do something like the following-

foo.each do |x|

Object.create(

3pm: x.3pm,

3pa: x.3pa

)

end

If I change it to '3pm' => x.3pm, it gives me a syntax error on the x.3pm portion.

How could I escape this to get it functioning?

网友答案:

The problem is that 3pm is not a valid identifier in Ruby. In Ruby, symbol literals declared with the :name syntax and method names must both be valid identifiers.

In the case of the keys, you can get around this by either using strings instead, as you discovered, or by using the :'name' syntax for symbol literals:

foo.each do |x|
 Object.create(
      :'3pm' => x.3pm,
      :'3pa' => x.3pa
    )
end

Unfortunately, this still leaves the problem of 3pm and 3pa not being valid method names. Normally, since those are not valid methods names, they couldn't even be methods on x in the first place. In this case though, x is likely using the either the define_method or method_missing features of Ruby to create or simulate the existance of a method named 3pm (even though that's normally not a valid method name in Ruby).

Thankfully, we can get around this by using Object#public_send to call the method:

foo.each do |x|
 Object.create(
      :'3pm' => x.public_send(:'3pm'),
      :'3pa' => x.public_send(:'3pa')
    )
end

That should resolve your problem.

相关阅读:
Top