John Smith
John Smith

Reputation: 6269

To Symbols but not in array

I generate an Array:

self.attributes.keys.map(&:to_sym) - [:created_at, :updated_at] + [:warte]  

The problem is, this code throws an error when I try to pass it to:

json.(self, self.attributes.keys.map(&:to_sym) - [:created_at, :updated_at] + [:warte] ) 

TypeError ([:id, :name, :vorname, ....] is not a symbol):

Because I would need the symbols simply split by ',':

 json.(self, :id, :name ....

And not in an Array like I have it now:

 json.(self, [:id, :name ....

What can I do to fix this?

Upvotes: 0

Views: 77

Answers (1)

Ajedi32
Ajedi32

Reputation: 48438

You're looking for the splat (*) operator:

json.(self, *(self.attributes.keys.map(&:to_sym) - [:created_at, :updated_at] + [:warte]))

According to ruby-doc.org, the splat operator may be used to convert arrays into argument lists:

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)

Source

Upvotes: 2

Related Questions