Skip to content

Instantly share code, notes, and snippets.

@satoryu
Created September 8, 2019 01:20
Show Gist options
  • Save satoryu/fe044a41e99a7bdbc97526d008a31fe0 to your computer and use it in GitHub Desktop.
Save satoryu/fe044a41e99a7bdbc97526d008a31fe0 to your computer and use it in GitHub Desktop.
a prototype of an inerface to convert object to hash
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