How can I rename the keys so that they are underscored
Here is a ruby hash:
a = {
:testOne => 1,
:开发者_如何转开发testTwo => 2
}
How can I rename the keys so that they are underscored?
a = {
:test_one => 1,
:test_two => 2
}
Ken Bloom got me on the right tract here. You do need ActiveSupport or Rails3. You don't need any specific gems for this solution however:
hash = Hash[a.map {|k,v| [k.to_s.underscore.to_sym, v]}]
Thanks ken!
Hash[a.map { |k,v| [k.to_s.downcase.sub('test','test_').to_sym, v] }]
Update: If you need to find the common root string, you can use this:
root = a.keys.inject do |m, e|
s = m.to_s
s.chop! while !e.to_s.start_with? s
s
end
This answer requires the facets gem, and activesupport (which is part of rails).
require 'active_support'
require 'facets'
a.map{|k,v| [k.to_s.underscore.to_sym, v]}.to_h
# ^^^^^^^^^^^ ^^^^ from facets
# from activesupport
精彩评论