Not really snippets, but I like these generic constructions (I show only how to use them, the implementation is easily found on the web).
Conversion Array -> Hash (to_hash
or mash
, the idea is the same, see Facets implementation):
>> [1, 2, 3].mash { |k| [k, 2*k] }
=> {1=>2, 2=>4, 3=>6}
Map + select/detect: You want to do a map and get only the first result (so a map { ... }.first
would inefficient):
>> [1, 2, 3].map_select { |k| 2*k if k > 1 }
=> [4, 6]
>> [1, 2, 3].map_detect { |k| 2*k if k > 1 }
=> 4
Lazy iterations (lazy_map, lazy_select, ...). Example:
>> 1.upto(1e100).lazy_map { |x| 2 *x }.first(5)
=> [2, 4, 6, 8, 10]