2012-02-25 33 views

回答

2

試試這個:

h.select {|key| [*0..9].map(&:to_s).include? key } 

記得我沒有爲你拉出值,它只是返回一個選擇你的哈希值與所期望的標準。像您習慣的那樣將這些哈希值拉出來。

1

如果 「數字」 是指整數,則:那麼

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"] 

你可能想調整正則表達式測試以允許前導和尾隨空白(或不)。

1

或者爲一個可能稍微更可讀但更長溶液中,嘗試:

 
    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?} 
2

另一種解決方案:

h.select {|k,v| k.to_i.to_s == k}.values 

這將返回的值是整數(正或負)的鍵。