RubyMapにメソッドを渡す方法

Oct 09 2020

私は次のコードを持っています:

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

私の場合:guestsはアクティブレコードテーブルですが、パススルーmapして生成したいカップルがありますuser_ids

したがって、私が渡したいのは、このようなメソッドの配列です。 [guests, bride, etc etc]

配列全体を渡すことができればさらに良いでしょうが、そうでなければ、メソッドの配列をステップスルーできればそれも素晴らしいでしょう。

何か案は?

編集:私は運がないのにこれを試しています..私は得る: 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

回答

2 PhiAgent Oct 09 2020 at 17:46

以下では、一連のメソッドを配列の結婚式のメンバーに渡します。

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