Created
September 8, 2019 01:20
-
-
Save satoryu/fe044a41e99a7bdbc97526d008a31fe0 to your computer and use it in GitHub Desktop.
a prototype of an inerface to convert object to hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def hash_from(obj, keys, options={}) | |
keys.inject({}) do |h, key| | |
v = obj.send(key) | |
h[key] = v unless options[:ignore_nil] && v.nil? | |
h | |
end | |
end | |
klass = Struct.new(:a, :b, :c) | |
obj1 = klass.new(1, 2, 3) | |
puts hash_from(obj1, %i[a b]) | |
puts hash_from(obj1, %i[a b c]) | |
obj2 = klass.new(1, 2) | |
puts hash_from(obj2, %i[a b c]) | |
puts hash_from(obj2, %i[a b c], { ignore_nil: true }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment