如何让ruby块返回块中的变量数组?
发布时间:2020-12-17 02:17:55 所属栏目:百科 来源:网络整理
导读:在ruby块中: user.trips.each { |trip| trip.pickedpost.user } 如何让代码返回一组用户? 如果我运行块 user.trips.each { |trip| puts trip.pickedpost.user } irb节目 #User:0x007fd1ab9e2148#User:0x007fd1aacf3dd8 = [#Trip id: 18,pickedpost_id: 25,
在ruby块中:
user.trips.each { |trip| trip.pickedpost.user } 如何让代码返回一组用户? 如果我运行块 user.trips.each { |trip| puts trip.pickedpost.user } irb节目 #<User:0x007fd1ab9e2148> #<User:0x007fd1aacf3dd8> => [#<Trip id: 18,pickedpost_id: 25,volunteer_id: 33,created_at: "2012-05-14 23:28:36",updated_at: "2012-05-14 23:28:36">,#<Trip id: 20,pickedpost_id: 20,created_at: "2012-05-15 00:12:39",updated_at: "2012-05-15 00:12:39">] 该块返回一个trip对象数组,这不是我想要的. 如何让块返回用户数组? 谢谢 解决方法
看起来你想要的是
.collect() 它:
user.trips.collect { |trip| trip.pickedpost.user } 或者使用.map() user.trips.map(&:pickedpost).map(&:user) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |