all_options = { :key1 => 1, :key2 => 2, :something_else => 42 }
my_keys = [:key1, :key2, :key3, :key4]
my_options = my_keys.inject({}) {|h,k| h[k] = all_options.delete(k) if all_options.key?(k);h}
all_options
# => {:something_else=>42}
my_options
# => {:key1=>1, :key2=>2}
这里有一种方法可以改进刘巨的回答:
all_options = { :key1 => 1, :key2 => 2, :something_else => 42 }
my_keys = [:key1, :key2, :key3, :key4]
my_options = all_options.extract!(*my_keys).keep_if {|k,v| v}
all_options
# => {:something_else=>42}
my_options
# => {:key1=>1, :key2=>2}
all_options
但是,如果哈希中的任何键的实际值为nil
or false
(不知道是否需要保留它们),您将失去选择:
all_options = { :key1 => 1, :key2 => nil, :something_else => 42 }
这是一种保持false
's 的方法
my_options = all_options.extract!(*my_keys).keep_if {|k,v| !v.nil?}
nil
ps如果您从以下位置存储密钥,则可以保留包括 s 在内的所有值all_options
:
all_options = { :key1 => 1, :key2 => 2, :something_else => 42 }
all_keys = all_options.keys
my_keys = [:key1, :key2, :key3, :key4]
my_options = all_options.extract!(*my_keys).keep_if {|k,v| all_keys.include?(k)}
all_options
# => {:something_else=>42}
my_options
# => {:key1=>1, :key2=>2}