Skip to content

Instantly share code, notes, and snippets.

@ukitazume
Created February 14, 2012 11:20
Show Gist options
  • Select an option

  • Save ukitazume/1825962 to your computer and use it in GitHub Desktop.

Select an option

Save ukitazume/1825962 to your computer and use it in GitHub Desktop.
class Hash
def values_classify
inject({}) do |options, (key, value)|
options[key] = value.class
options
end
end
def values_classify!
replace(self.values_classify)
end
def values_classify_recursive
inject({}) do |options, (key, value)|
if value.instance_of?(Hash)
options[key] = value.values_classify_recursive
else
options[key] = value.class
end
options
end
end
def replace_by_path(path, replae_value)
inject({}) do |options, (key, value)|
if path.instance_of?(Array) and path.first == key
path.shift
if path.empty?
options[key] = replae_value
else
options[key] = self[key].replace_by_path(path, replae_value)
end
else
options[key] = value
end
options
end
end
end
hash = {:aa => 'aa', :hash => {:foo => 'iaa'}, :bar => 'bar'}
hash.replace_by_path([:hash, :foo], "replacemenet")
#=> {:bar=>"bar", :hash=>{:foo=>"replacemenet"}, :aa=>"aa"}
hash.values_classify #= > {:bar=>String, :hash=>Hash, :aa=>String}
hash.values_classify_recursive #= > {:bar=>String, :hash=>{:foo=>String}, :aa=>String}
hash.values_classify!
hash #= > {:bar=>String, :hash=>Hash, :aa=>String}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment