Skip to content

Instantly share code, notes, and snippets.

@earlonrails
Last active October 1, 2015 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save earlonrails/2048705 to your computer and use it in GitHub Desktop.
Save earlonrails/2048705 to your computer and use it in GitHub Desktop.
Some simple hash methods for ruby 1.9.x
# simple hash methods for ruby 1.9.x
# maybe for rails object attributes :D
# for creating a similar user date time as a string can break in some cases or maybe just skip things you don't need
# ie:
# attributes = simplify_record(User.first.attributes, [:attributes, :i, :need, :and, :not, :date_time_string])
# User.create(attributes)
def simplify_record(hash, keep)
hash.keep_if { |key| keep.include?(key) }
end
# same as above but for an array
def simplify_array(array, keep)
array.collect { |value| simplify_record(value, keep) }
end
# examples
example_hash = {:a => 1, :b => 2, :c => 3}
array_of_hashes = [example_hash, example_hash]
simplify_record(example_hash, [:a, :b])
# => {:a => 1, :b => 2}
simplify_array(array_of_hashes, [:b, :c])
# => [{:b => 2, :c => 3}, {:b => 2, :c => 3}]
# recursive/deep remove keys
def deep_simplify_record(hash, keep)
hash.keep_if do |key, value|
if value.is_a?(Hash)
deep_simplify_record(value, keep)
else
keep.include?(key)
end
end
end
example_hash_recursive = {:a => 1, :b => 2, :c => {:a => 1, :b => 2, :c => {:a => 1, :b => 2, :c => 4}} }
deep_simplify_record(example_hash_recursive, [:b, :c])
# => {:b=>2, :c=>{:b=>2, :c=>{:b=>2, :c=>4}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment