Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby object to hash
class Foo
attr_reader :alpha
def initialize
@alpha = 1
@bravo = 2
end
end
foo = Foo.new
# This works, but returns even instance variables that aren't public
foo.instance_variables.map { |x| [x.to_s.delete('@'), foo.instance_variable_get(x)] }.to_h
# > {'alpha': 1, 'bravo': 2}
# This works, but doesn't account for cases where the attribute only incidentally has the same name
foo.instance_variables.select do |x|
foo.respond_to? x.to_s.delete('@')
end.map do |x|
[x.to_s.delete('@'), foo.instance_variable_get(x)]
end.to_h
# > {'alpha': 1}
class Bar
attr_reader :alpha
attr_reader :charlie
def initialize
@alpha = 1
@bravo = 2
@charlie = 3
end
def charlie
:masked_value
end
end
bar = Bar.new
bar.instance_variables.select do |x|
bar.respond_to? x.to_s.delete('@')
end.map do |x|
[x.to_s.delete('@'), bar.instance_variable_get(x)]
end.to_h
# > {'alpha': 1, 'charlie': :masked_value}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment