Skip to content

Instantly share code, notes, and snippets.

@hagiyat
Created July 24, 2015 03:18
Show Gist options
  • Save hagiyat/454a07bbc18c5cd88eb4 to your computer and use it in GitHub Desktop.
Save hagiyat/454a07bbc18c5cd88eb4 to your computer and use it in GitHub Desktop.
source = {
hoge: { piyo: {
piyo1: 'piyo1',
piyo2: 'piyo2'
}, baz: 'baz' },
fuga: { foo: 'foo', bar: 'bar' }
}
fetch_hash = ->(source, key, separator='_') do
key.split(separator)
.reduce(source) { |msg, v| msg[v.to_sym] || {} }
.tap{ |v| break nil unless v.is_a? String }
end.curry.(source)
fetch_hash.('fuga_foo') # foo
fetch_hash.('hoge_piyo_piyo2') # piyo2
fetch_hash.('fuga_hoge') # nil
fetch_hash.('hoge') # nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment