Cách chuyển các phương thức vào Ruby Map

Oct 09 2020

Tôi có mã sau:

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

Trong trường hợp của tôi :guestslà một bảng ghi đang hoạt động, nhưng tôi có một số mà tôi muốn chuyển qua mapđể tạouser_ids

Vì vậy, nó sẽ là một mảng các phương thức như thế này, mà tôi muốn chuyển: [guests, bride, etc etc]

Sẽ tốt hơn nữa nếu tôi có thể chuyển toàn bộ mảng, nhưng ngược lại nếu tôi có thể chuyển qua mảng các phương thức cũng sẽ rất tuyệt.

Có ý kiến ​​gì không?

CHỈNH SỬA: Tôi đang thử điều này nhưng không may mắn .. Tôi nhận được: 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

Trả lời

2 PhiAgent Oct 09 2020 at 17:46

Dưới đây, tôi truyền một mảng các phương thức cho các thành viên của đám cưới mảng:

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