6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby Hashのグループ化

Posted at

始めに

RubyでHashのkey,Valueの組み合わせをグループ化してみます

やりたいこと

[{"test"=>"1"},{"test"=>"1"},{"test1"=>"2"}]
を```
{"test"=>["1", "1"]}
{"test1"=>["2"]}


# 実装
```groupbytest.rb
p =  [{"test"=>"1"},{"test"=>"1"},{"test1"=>"2"}]
.group_by do |name| 
  name.keys[0]
end
.collect do |k,v|
    {k=>v.collect{|h|h.values[0]}}
end

puts p

雑感

同じようなことを
Listに含まれる単語の数をカウントするプログラム
の記事でJavaで実装したけれど、
JavaのCollectors.groupingByのような第二引数にグループ化のロジックが書けるメソッドがRubyにあればもっとシンプルロジックは書けるのだけど

6
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?