过滤哈希的键

时间:2013-06-29 11:17:13

标签: ruby hash

我在hashes变量中有这些哈希值:

{:priority=>100, :iso_code=>"JPY", :name=>"Japanese Yen", :symbol=>"¥", :alternate_symbols=>["円", "圓"], :subunit=>"Sen", :subunit_to_unit=>100, :symbol_first=>true, :html_entity=>"¥", :decimal_mark=>".", :thousands_separator=>",", :iso_numeric=>""}
{:priority=>100, :iso_code=>"ZWD", :name=>"Zimbabwean Dollar", :symbol=>"$", :alternate_symbols=>["Z$"], :subunit=>"Cent", :subunit_to_unit=>100, :symbol_first=>true, :html_entity=>"$", :decimal_mark=>".", :thousands_separator=>",", :iso_numeric=>"716"}
{:priority=>100, :iso_code=>"ZWL", :name=>"Zimbabwean Dollar", :symbol=>"$", :alternate_symbols=>["Z$"], :subunit=>"Cent", :subunit_to_unit=>100, :symbol_first=>true, :html_entity=>"$", :decimal_mark=>".", :thousands_separator=>",", :iso_numeric=>"932"}
{:priority=>100, :iso_code=>"ZWN", :name=>"Zimbabwean Dollar", :symbol=>"$", :alternate_symbols=>["Z$"], :subunit=>"Cent", :subunit_to_unit=>100, :symbol_first=>true, :html_entity=>"$", :decimal_mark=>".", :thousands_separator=>",", :iso_numeric=>"942"}
{:priority=>100, :iso_code=>"ZWR", :name=>"Zimbabwean Dollar", :symbol=>"$", :alternate_symbols=>["Z$"], :subunit=>"Cent", :subunit_to_unit=>100, :symbol_first=>true, :html_entity=>"$", :decimal_mark=>".", :thousands_separator=>",", :iso_numeric=>"935"}

我想用三个键来填充/更新hashes变量:

:iso_code
:name
:symbol

我该怎么做?

2 个答案:

答案 0 :(得分:2)

{:priority=>100, :iso_code=>"JPY", :name=>"Japanese Yen", :symbol=>"¥", :alternate_symbols=>["円", "圓"], :subunit=>"Sen", :subunit_to_unit=>100, :symbol_first=>true, :html_entity=>"¥", :decimal_mark=>".", :thousands_separator=>",", :iso_numeric=>""}
.select{|k, _| [:iso_code, :name, :symbol].include?(k)}
# => {:iso_code=>"JPY", :name=>"Japanese Yen", :symbol=>"¥"}

答案 1 :(得分:0)

您还可以使用keep_if哈希方法

1.9.3p392 :001 > hsh = {:priority=>100, :iso_code=>"JPY", :name=>"Japanese Yen", :symbol=>"¥", :alternate_symbols=>["円", "圓"], :subunit=>"Sen", :subunit_to_unit=>100, :symbol_first=>true, :html_entity=>"¥", :decimal_mark=>".", :thousands_separator=>",", :iso_numeric=>""}
 => {:priority=>100, :iso_code=>"JPY", :name=>"Japanese Yen", :symbol=>"¥", :alternate_symbols=>["円", "圓"], :subunit=>"Sen", :subunit_to_unit=>100, :symbol_first=>true, :html_entity=>"¥", :decimal_mark=>".", :thousands_separator=>",", :iso_numeric=>""} 
1.9.3p392 :002 > hsh.keep_if {|key,value| ([:iso_code, :name, :symbol]).include?(key)}
 => {:iso_code=>"JPY", :name=>"Japanese Yen", :symbol=>"¥"}