Skip to content

Instantly share code, notes, and snippets.

@matsuda
Created January 5, 2011 06:00
Show Gist options
  • Save matsuda/765989 to your computer and use it in GitHub Desktop.
Save matsuda/765989 to your computer and use it in GitHub Desktop.
hash_with_underscore_key is only converting key on Hash into underscore.
class Array
def to_underscore_key
self.class.new.tap do |array|
self.each { |value|
case value
when Hash, Array
array << value.to_underscore_key
else
array << value
end
}
end
end
end
class Hash
def to_underscore_key
self.class.new.tap do |hash|
self.each_pair { |key, value|
case key
when Hash, Array, String, Symbol
case value
when Hash, Array
hash[key.to_underscore_key] = value.to_underscore_key
else
hash[key.to_underscore_key] = value
end
else
case value
when Hash, Array
hash[key] = value.to_underscore_key
else
hash[key] = value
end
end
}
end
end
end
class String
def to_underscore_key
self.underscore.gsub(/([^\d\s]+)(\d)/, "\\1_\\2")
end
end
class Symbol
def to_underscore_key
self.to_s.to_underscore_key.to_sym
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment