Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, group_by where I know there's only 1 element per group

Tags:

ruby

I have a CSV file where one column is a primary key. When I do this:

CSV.read(ARGV[0], headers: true).group_by {|r| r['myKey']}

I get a hash table from key to a list of rows, where the list is always length 1.

Is there a version of group_by which asserts that there's only a single value per key, and creates a hash from key to that single value?

Failing that, is there something like .first which asserts that there's exactly one element in the array/enumerable? I like my scripts to fail when my assumptions are wrong, rather than silently return the wrong thing.

like image 401
Martin C. Martin Avatar asked Jan 23 '15 18:01

Martin C. Martin


1 Answers

If you use Rails you can use index_by method.

like image 147
Bogdan Guban Avatar answered Oct 05 '22 23:10

Bogdan Guban