到符号但不在数组中
To Symbols but not in array
我生成一个数组:
self.attributes.keys.map(&:to_sym) - [:created_at, :updated_at] + [:warte]
问题是,当我尝试将此代码传递给以下代码时会引发错误:
json.(self, self.attributes.keys.map(&:to_sym) - [:created_at, :updated_at] + [:warte] )
TypeError ([:id, :name, :vorname, ....] is not a symbol):
因为我需要简单地用','分隔的符号:
json.(self, :id, :name ....
而不是像我现在这样在数组中:
json.(self, [:id, :name ....
我该怎么做才能解决这个问题?
您正在寻找 splat (*
) 运算符:
json.(self, *(self.attributes.keys.map(&:to_sym) - [:created_at, :updated_at] + [:warte]))
According to ruby-doc.org,splat 运算符可用于将数组转换为参数列表:
Array to Arguments Conversion
Given the following method:
def my_method(argument1, argument2, argument3)
end
You can turn an Array into an argument list with * (or splat)
operator:
arguments = [1, 2, 3]
my_method(*arguments)
or:
arguments = [2, 3]
my_method(1, *arguments)
Both are equivalent to:
my_method(1, 2, 3)
我生成一个数组:
self.attributes.keys.map(&:to_sym) - [:created_at, :updated_at] + [:warte]
问题是,当我尝试将此代码传递给以下代码时会引发错误:
json.(self, self.attributes.keys.map(&:to_sym) - [:created_at, :updated_at] + [:warte] )
TypeError ([:id, :name, :vorname, ....] is not a symbol):
因为我需要简单地用','分隔的符号:
json.(self, :id, :name ....
而不是像我现在这样在数组中:
json.(self, [:id, :name ....
我该怎么做才能解决这个问题?
您正在寻找 splat (*
) 运算符:
json.(self, *(self.attributes.keys.map(&:to_sym) - [:created_at, :updated_at] + [:warte]))
According to ruby-doc.org,splat 运算符可用于将数组转换为参数列表:
Array to Arguments Conversion
Given the following method:
def my_method(argument1, argument2, argument3) end
You can turn an Array into an argument list with * (or splat) operator:
arguments = [1, 2, 3] my_method(*arguments)
or:
arguments = [2, 3] my_method(1, *arguments)
Both are equivalent to:
my_method(1, 2, 3)