ToddT
ToddT

Reputation: 3258

How to pass methods to Ruby Map

I have the following code:

wedding = Wedding.where(location_id: user_params[:locationId])
wedding.map(&:guests).each do |member|
  user_ids << member.ids
end

In my case :guests is a active record table, but I have a couple that I would like to pass thru map to generate the user_ids

So it would be array of methods like this, that I would like to pass: [guests, bride, etc etc]

It would be even better if I could pass the whole array, but otherwise if I can step through the array of methods that would be great too.

Any ideas?

EDIT: I'm trying this with no luck.. I get: NameError (wrong constant name guests):

roles = ["guests"]
  wedding = Wedding.where(location_id: user_params[:locationId])
  roles.each do |role|
    clazz = Kernel.const_get(role)
    wedding.map(&:clazz).each do |member|
      user_ids << member.ids
    end
 end

Upvotes: 1

Views: 131

Answers (1)

PhiAgent
PhiAgent

Reputation: 158

Below, i pass an array of methods to members of the array weddings:

weddings = Wedding.where(location_id: user_params[:locationId])

# array with methods you're interested in
methods=[:guests, :bride]

# looping through the weddings array
weddings.each do |wedding|
  
#   looping through the methods array
  methods.each do |method|
    
#     for each wedding, passing every method to the wedding
    members=wedding.public_send(method)
    members.each do |member|
      
#       storing the values
      user_ids << member.ids
    end
  end
end


Upvotes: 2

Related Questions