转换哈希数组中的值的最佳方法(性能)

问题描述 投票:0回答:3

给出:

data = [
  {"votable_id"=>1150, "user_ids"=>"1,2,3,4,5,6,"},
  {"votable_id"=>1151, "user_ids"=>"55,66,34,23,56,7,8"}
]

这是预期的结果。数组应包含前 5 个元素。

data = [
  {"votable_id"=>1150, "user_ids"=>["1","2","3","4","5"]},
  {"votable_id"=>1151, "user_ids"=>["55","66","34","23","56","7",8"]}
]

这是我尝试过的:

data.map{|x| x['user_ids'] = x['user_ids'].split(',').first(5)}

还有其他优化方案吗?

ruby-on-rails arrays ruby hash
3个回答
4
投票

您还可以像这样使用

.map
.tap

data.map do |h|
 h.tap { |m_h| m_h["user_ids"]= m_h["user_ids"].split(',').first(5)}
end

1
投票
data = [
    {"votable_id"=>1150, "user_ids"=>"1,2,3,4,5,6,"},
    {"votable_id"=>1151, "user_ids"=>"55,66,34,23,56,7,8"}
]

代码

h=data.map do |h|
  h["user_ids"]=[h["user_ids"].split(',').first(5)].flatten
  h
end

p h

输出

[{"votable_id"=>1150, "user_ids"=>["1", "2", "3", "4", "5"]}, {"votable_id"=>1151, "user_ids"=>["55", "66", "34", "23", "56"]}]

1
投票
data.map { |h| h.merge("user_ids"=>h["user_ids"].split(',').first(5)) }
  #=> [{"votable_id"=>1150, "user_ids"=>["1", "2", "3", "4", "5"]},
  #    {"votable_id"=>1151, "user_ids"=>["55", "66", "34", "23", "56"]}] 

请参阅哈希#merge。这使得

data
保持不变。要修改(或变异
data
,请使用Hash#merge!(又名
update
)。
h.merge(k=>v)
h.merge({ k=>v })
的快捷方式。

© www.soinside.com 2019 - 2024. All rights reserved.