本文介绍了红宝石数组。 group_by并在一行中修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[{:type =>Meat,:name = >one},
{:type =>Meat,:name =>two},
{:type =>Fruit,:name => four}]
我想将它转换为
{Meat=> [one,two],Fruit=> [Four]}
我试过 group_by
然后我得到了这个
{Meat=> [{:type =>Meat,:name =>one},{:type =>Meat,::name =>two}],
Fruit > [{:type =>Fruit,:name =>four}]}
然后我无法修改它只留下名称而不是完整的散列。我需要在一行中执行此操作,因为在Rails表单上的 grouped_options_for_select
。
解决方案
array.group_by {| H | h [:type]}。each {| _,v | v.replace(v.map {| h | h [:name]})}
#=> {Meat=> [one,two],Fruit=> [four]}
以下是steenslag的建议:
array.group_by {| h | h [:type]}。each {| _,v | v.map {|!H | h [:name]}}
#=> {Meat=> [one,two],Fruit=> [four]}
I have an array of hashes, something like
[ {:type=>"Meat", :name=>"one"},
{:type=>"Meat", :name=>"two"},
{:type=>"Fruit", :name=>"four"} ]
and I want to convert it to this
{ "Meat" => ["one", "two"], "Fruit" => ["Four"]}
I tried group_by
but then i got this
{ "Meat" => [{:type=>"Meat", :name=>"one"}, {:type=>"Meat", :name=>"two"}],
"Fruit" => [{:type=>"Fruit", :name=>"four"}] }
and then I can't modify it to leave just the name and not the full hash. I need to do this in one line because is for a grouped_options_for_select
on a Rails form.
解决方案
array.group_by{|h| h[:type]}.each{|_, v| v.replace(v.map{|h| h[:name]})}
# => {"Meat"=>["one", "two"], "Fruit"=>["four"]}
Following steenslag's suggestion:
array.group_by{|h| h[:type]}.each{|_, v| v.map!{|h| h[:name]}}
# => {"Meat"=>["one", "two"], "Fruit"=>["four"]}
这篇关于红宝石数组。 group_by并在一行中修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!