I had an instance where I'd written some code, using hashes, and knew that there had to be a better way to do it. Performing an inject and adding elements to a hash doesn't work:
h[a] = 1
returns the value, not the hash. Here's the smelly code (variables, etc., changed to protect the guilty):
# possibilities is an array
def intersectors(possibilities = [], interceptors = [])
return { } if possibilities.nil?
interceptors.inject({ }) do |h, interceptor|
# returns an array
z = foo(interceptor)
intersect = possibilities & z
h[interceptor] = intersect unless intersect.empty?
h
end
end
So, then I decided to RTFM and found merge. It makes it a lot tighter:
def intersectors(path = [], interceptors = [])
return { } if path.nil?
interceptors.inject({ }) do |h, interceptor|
h.merge(interceptor => x) unless (x=(path & foo(interceptor))).empty?
end
end
Better, too, I think; I don't have that extraneous h laying around..... I'm also using some syntactic sugar -- ruby is smart enough to make a hash of key/value pairs in a method call, so long as they're the last entities to be passed.
I'm not saying it's baby-fresh, but it certainly stinks less.....