【问题标题】:I would like to know the best way to implement the following我想知道执行以下操作的最佳方法
【发布时间】:2015-01-01 21:54:42
【问题描述】:

我有一组用户数据,我想获取所有这些用户的名字。我们可以简单地使用

user_list.map(&:first_name)

对于中间名和姓氏,我也需要这样做

user_list.map(&:middle_name)
user_list.map(&:last_name)

正如我们在这里看到的,我必须对相同的数据循环 3 次才能收集名字、中间名和姓氏。谁能建议我一种可以在一个循环中做到这一点的方法。

所以输出会是这样的。

{first_name: ["tom", "harry", "ronald"], middle_name: ["marvello", "james", "bilius"], last_name: ["riddle", "potter", "weasley"] }

PS,它不是使用 pluck 的活动记录调用。它是我需要运行它的记录集合,而不是活动记录调用。

【问题讨论】:

  • 问一个问题时,试着想出一个标题来表明你在问什么。 “我想知道实现以下内容的最佳方法”什么也没告诉我们。也许“如何将对象属性收集到数组中”会告诉搜索者一些事情。
  • @theTinMan 会记住的。谢谢

标签: ruby-on-rails ruby arrays hash enumerable


【解决方案1】:

一个明显的解决方案是each 循环:

names = {first_name: [], middle_name: [], last_name: []}    
user_list.each do |user|
  names[:first_name] << user.first_name
  names[:middle_name] << user.middle_name
  names[:last_name] << user.last_name
end

或者使用each_with_object:

user_list.each_with_object(first_name: [], middle_name: [], last_name: []) do |user, names|
  names[:first_name] << user.first_name
  names[:middle_name] << user.middle_name
  names[:last_name] << user.last_name
end

【讨论】:

  • 我目前只用每个循环实现了它,但是 each_with_object 看起来不错,din 知道这一点。谢谢
【解决方案2】:
user_attributes = ['first_name','middle_name','last_name']
# A hash to hold final result
hsh = HashWithIndifferentAccess.new
user_attributes.each do |attr|
  hsh[attr] = user_list.collect {|i| i.send(attr)}
end 
#Result
#$hsh
#{first_name: [...],middle_name: [...],last_name: [...]}

更新

由于上面的答案有 3 次迭代,你可以通过 flat_map 单次完成

user_attributes = [:first_name,:middle_name,:last_name]
collection = user_list.flat_map { |user| [{first_name: user.first_name,middle_name: user.middle_name,last_name: user.last_name}] }


# A hash to hold final result, as u need then as collection. aggregating the independent keys
hsh = HashWithIndifferentAccess.new
user_attributes.each {|attr| hsh[attr] = collection.collect {|i| i[attr] }

【讨论】:

  • 那还是3次迭代。
  • @SergioTulentsev,感谢指点,用平面地图试了另一张
【解决方案3】:

看看pluck

user_list.pluck(:first_name, :middle_name, :last_name)

它适用于 ActiveRecord 结果。

【讨论】:

  • 它不是一个活跃的录音电话,抱歉我没有提到它。我已经有一个需要运行它的集合。
猜你喜欢
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2017-10-30
  • 2012-10-02
相关资源
最近更新 更多