3 ms·
Gems of Python
- ivankirigin 18y agoI didn't know about defaultdict. The setdefault method was clunky, but that looks really clean.
- newt0311 18y agoDefaultdict and friends were one of the benefits of completing the object model of python. It is made by subclassing userdict and effective.
- tptacek 18y agoThese are all pretty straightforward (and in some cases, rusty) examples, but I am required by the Rubonics Institute to write this response: 1. ["1", "2", "asdf", "3"].reject {|x| begin; Integer(x); rescue; false; else; true} => ["1", "2", "3"] 2. [[1,2,3], [4,5,6]].flatten.sum => 21 3. tbl = Hash.new {|d, k| d[k] = []} 4. tbl["foo"] << 1 => ["foo"] 5. ["a", "b", "c"].zip([1,2,3]) => [["a", 1], ["b", 2], ["c", 3]] 6. "the little green men".titleize => "The Little Green Men" Obligatory snarky aside: these aren't hidden gems in Ruby (well, except for String#titleize, which is an activesupport extension, so only Rails devs see it by default). They're baked in.