說我有一個像哈希:獲取來自哈希數字鍵紅寶石
h = { '0' => 'foo', 'bar' => 'baz' => '2' => 'yada' }
我怎麼會去判斷這個哈希中有任何數字鍵,拉出那些鍵的值是多少?
說我有一個像哈希:獲取來自哈希數字鍵紅寶石
h = { '0' => 'foo', 'bar' => 'baz' => '2' => 'yada' }
我怎麼會去判斷這個哈希中有任何數字鍵,拉出那些鍵的值是多少?
試試這個:
h.select {|key| [*0..9].map(&:to_s).include? key }
記得我沒有爲你拉出值,它只是返回一個選擇你的哈希值與所期望的標準。像您習慣的那樣將這些哈希值拉出來。
如果 「數字」 是指整數,則:那麼
a = h.each_with_object([]) { |(k, v), a| a << v if(k.to_i.to_s == k) }
如果 「數字」 還包括浮點值:
h.each_with_object([]) { |(k, v), a| a << v if(k =~ /\A[+-]?\d+(\.\d+)?\z/) }
例如:
>> h = { '0' => 'foo', 'bar' => 'baz', '2' => 'yada', '-3.1415927' => 'pancakes' }
=> {"0"=>"foo", "bar"=>"baz", "2"=>"yada", "-3.1415927"=>"pancakes"}
>> h.each_with_object([]) { |(k, v), a| a << v if(k =~ /\A[+-]?\d+(\.\d+)?\z/) }
=> ["foo", "yada", "pancakes"]
你可能想調整正則表達式測試以允許前導和尾隨空白(或不)。
或者爲一個可能稍微更可讀但更長溶液中,嘗試:
class String def is_i? # Returns false if the character is not an integer each_char {|c| return false unless /[\d.-]/ =~ c} # If we got here, it must be an integer true end end h = {"42"=>"mary", "foo"=>"had a", "0"=>"little", "-3"=>"integer"} result = [] h.each {|k, v| result << v if k.is_i?}
另一種解決方案:
h.select {|k,v| k.to_i.to_s == k}.values
這將返回的值是整數(正或負)的鍵。