Last active
September 6, 2017 14:09
-
-
Save lyndsysimon/dfa513f92d6711f6b55056763ba94f44 to your computer and use it in GitHub Desktop.
Ruby object to hash
This file contains hidden or 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
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