Skip to content

Instantly share code, notes, and snippets.

@jeanlescure
Last active August 29, 2015 14:17
Show Gist options
  • Save jeanlescure/b022901d0957b9936c03 to your computer and use it in GitHub Desktop.
Save jeanlescure/b022901d0957b9936c03 to your computer and use it in GitHub Desktop.
Stringify booleans recusively in Arrays and Hashes
# 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
@jeanlescure
Copy link
Author

Added ArgumentError exception, replaced if comparison with case comparison for added performance. 🔫

@jeanlescure
Copy link
Author

I was completely wrong, if statement performs better than case ( as per this article )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment