Skip to content

Instantly share code, notes, and snippets.

@3014zhangshuo
Created March 26, 2018 03:59
Show Gist options
  • Save 3014zhangshuo/9a352203df5f2c4d6ff55c607694288c to your computer and use it in GitHub Desktop.
Save 3014zhangshuo/9a352203df5f2c4d6ff55c607694288c to your computer and use it in GitHub Desktop.
ruby hash without method
# source: https://apidock.com/ruby/Hash/delete
class Hash
def without(*keys)
cpy = self.dup
keys.each { |key| cpy.delete(key) }
cpy
end
end
h = { :a => 1, :b => 2, :c => 3 }
h.without(:a) #=> { :b => 2, :c => 3 }
h.without(:a, :c) #=> { :b => 2 }
class Hash
def without(*keys)
dup.without!(*keys)
end
def without!(*keys)
reject! { |key| keys.include?(key) }
end
end
h = { :a => 1, :b => 2, :c => 3 }
h.without(:a) #=> { :b => 2, :c => 3 }
h #=> { :a => 1, :b => 2, :c => 3 }
h.without(:a, :c) #=> { :b => 2 }
h.without!(:a, :c) # { :b => 2 }
h #=> { :b => 2 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment