Skip to content

Instantly share code, notes, and snippets.

@pjb3
pjb3 / gist:5279741
Last active December 15, 2015 15:09
Default values in Hashes
# The inner Hash.new(0) will now be the object that returned
# when you try to fetch the value for a key that doesn't exist
>> h = Hash.new(Hash.new(0))
=> {}
# When you do this, you are mutating the object that is the default value
# of the Hash and not changing the Hash itself
>> h[:foo][10] += 1
=> 1
@ddemaree
ddemaree / 01_README.md
Created November 30, 2011 05:23
How Sunspot implements its wonderful search/index DSL

This code is extracted/adapted from Mat Brown's Sunspot gem. One of Sunspot's nicest features is an expressive DSL for defining search indexes and performing queries. It works by instance_eval-ing a block you pass into it in the context of its own search builder object. In this code, the pig thing1 statement is roughly equivalent to zoo = Zoo.new; zoo.pig(thing1).

Sunspot's DSL has to resort to trickery: the instance_eval_with_context method uses eval to get the block to give up the object it considers to be self, then sets up an elaborate system of delegates and method_missing calls so any methods not handled by the DSL are forwarded to the surrounding object. But as a result, this syntax is minimal and beautiful, and it works the way you expect whether or not you prefer blocks to yield an object.

Without this trick the block would be restricted to either the original, "calling" context (as a closure) or the DSL's "receiving" context (using instance_eval), but not both.

Using `ins

@johnbintz
johnbintz / helper.coffee
Created June 14, 2011 20:32
Make Backbone report validation errors, much like @model.save! in Rails
class Backbone.ValidatingModel extends Backbone.Model
_performValidation: (attrs, options = {}) ->
_options = _.clone(options)
_options.error = (model, error, opts) ->
throw new Error(error)
super(attrs, _options)
from string import digits
x = ["1a", "2b", "2b", "3c", "5e"]
#the clearest, most basic way I can think of
numbers = {}
for i in x:
first = i[0]
if first in digits:
if first in numbers: