首页 > 解决方案 > 在 Map 函数中的符号内传递方法

问题描述

有人可以向我解释,我如何在给我 Map 的符号内传递一个方法。这是我的方法

def visited_venues
  Profile.find(1432).bookings.map(&:venue).uniq
end

现在我想做类似的事情

def visited_venues
 Profile.find(1432).bookings.map(&:venue.kept).uniq
end

这会在我的数据库中返回我所有未丢弃的内容,当我尝试这样做时,总是返回我undefined,因为地点是一个符号。感谢您的任何帮助和解释。

标签: ruby-on-railsarraysrubydictionarymethods

解决方案


而不是做

Profile.find(1432).bookings.map(&:venue.kept).uniq

尝试

Profile.find(1432).bookings.map { |booking| booking.venue.kept }.uniq

在 Pry 中进行测试

["hi", "bye"].map(&:upcase) -> ["HI", "BYE"]
["hi", "bye"].map(&:upcase.downcase) -> ["HI", "BYE"]

请记住

(&:method) is just a shortcut for { |el| el.method }

推荐阅读