[英]Grouping hashes by a key value while merging the other key values into a string
I've seen a lot of similar questions around, but this is a very specific case. 我已经看到很多类似的问题,但这是一个非常具体的情况。
What I have as input: 我输入的内容:
entries = [
{:action=>"X", :sequence=>1},
{:action=>"Y", :sequence=>2},
{:action=>"W", :sequence=>2},
{:action=>"Z", :sequence=>3}
]
What I want as output (join actions by sequence with "and" and all actions with ", "): 我想要的输出(按顺序将动作与“和”和所有动作与“,”一起加入):
"X, Y and W, Z"
How I've done it: 我是如何做到的:
group = entries.group_by {|x| x.delete(:sequence)}.values
=> [[{:action=>"X"}], [{:action=>"Y"}, {:action=>"W"}], [{:action=>"Z"}]]
array = group.map { |el| el.map { |h| h[:action] } }
=> [["X"], ["Y", "W"], ["Z"]]
string = array.map { |a| a.join(' and ') }.join(', ')
=> "X, Y and W, Z"
It works, but its far from being clean. 它可以工作,但远非干净。 Does anyone have a better solution?
有谁有更好的解决方案?
The below is the shortest one I can think of: 以下是我能想到的最短的一种:
entries.group_by { |e| e.delete :sequence }
.values
.map { |e| e.map(&:values).join ' and ' }
.join ', '
Another one [non-destructive]: 另一个[非破坏性]:
entries.map(&:values)
.group_by(&:last)
.values
.map { |e| e.map(&:first).join ' and ' }
.join ', '
And even: 乃至:
entries.map(&:values)
.group_by(&:pop)
.values
.map { |e| e.join ' and ' }
.join ', '
Or you may play with each_with_object
method: 或者,您可以使用
each_with_object
方法:
entries.each_with_object(Hash.new {[]}) do |e, m|
m[e[:sequence]] <<= e[:action]
end.values
.map{|e| e.join(' and ')}
.join(", ")
#=> "X, Y and W, Z"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.