Ruby Map에 메소드를 전달하는 방법

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