Skip to content

Instantly share code, notes, and snippets.

@colinrymer
Created May 8, 2013 17:38
Show Gist options
  • Save colinrymer/5542121 to your computer and use it in GitHub Desktop.
Save colinrymer/5542121 to your computer and use it in GitHub Desktop.

###Given

  DEFAULTS = {
    foo: lambda { ENV['FOO'] },
    bar: lambda { ENV['BAR'] },
    bazz: 0.1
  }

##Which is preferred:

defaults = DEFAULTS.each_with_object({}) do |(k, v), hash|
  hash[k] = v.respond_to?(:call) ? v.call : v
end

OR

defaults = DEFAULTS.dup

defaults.each do |k, v|
  defaults[k] = v.call if v.respond_to?(:call)
end
@databyte
Copy link

databyte commented May 8, 2013

I prefer the first because each_with_object is like a map to me, easy to identify with and read. My hang up is with what's in the block.

How about...

defaults = DEFAULTS.each_with_object({}) {|(k, v), hash| call_or_assign_values k, v, hash }

def call_or_assign_values k, v, hash
  hash[k] = v.respond_to?(:call) ? v.call : v
end

I'm sure there's an iteration or two there but anytime I have to read and "process" something mentally, I always wonder if I can give it a name and abstract it.

@colinrymer
Copy link
Author

I like the idea of extracting out the logic into a new method, especially since it makes a nice one liner, and we know how I feel about one line methods. :trollface:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment