Last active
August 29, 2015 14:17
-
-
Save jeanlescure/b022901d0957b9936c03 to your computer and use it in GitHub Desktop.
Stringify booleans recusively in Arrays and Hashes
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
# Over-write method | |
def stringify_bools!(target) | |
target.replace stringify_bools(target) | |
end | |
# Returns clone of target Array or Hash with all booleans within turned into strings | |
def stringify_bools(target) | |
t_clone = target.clone | |
raise ArgumentError, 'Target is neither Array or Hash' unless target.is_a?(Array) || target.is_a?(Hash) | |
t_class = target.class.to_s | |
if t_class == 'Array' | |
t_clone.map! do |el| | |
el = el.to_s if el.is_a?(TrueClass) || el.is_a?(FalseClass) | |
el = stringify_bools(el) if el.is_a?(Array) || el.is_a?(Hash) | |
el | |
end | |
elsif t_class == 'Hash' | |
t_clone.each do |key, val| | |
t_clone[key] = val.to_s if val.is_a?(TrueClass) || val.is_a?(FalseClass) | |
t_clone[key] = stringify_bools(val) if val.is_a?(Array) || val.is_a?(Hash) | |
end | |
end | |
t_clone | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was completely wrong, if statement performs better than case ( as per this article )