-2

私はこれらのハッシュを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"}

hashes3 つのキーのみで変数を入力/更新したい:

:iso_code
:name
:symbol

どうすればいいですか?

4

2 に答える 2

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=>"¥"}
于 2013-06-29T11:26:54.680 に答える
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=>"¥"} 
于 2013-06-29T11:39:21.710 に答える