Say I have a hash like:
h = { '0' => 'foo', 'bar' => 'baz' => '2' => 'yada' }
How would I go about determining if this hash has any numeric keys in it and pulling out the values of those keys?
If "numeric" means integer then:
a = h.each_with_object([]) { |(k, v), a| a << v if(k.to_i.to_s == k) }
If "numeric" also includes floating point values then:
h.each_with_object([]) { |(k, v), a| a << v if(k =~ /\A[+-]?\d+(\.\d+)?\z/) }
For example:
>> 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"]
You might want to adjust the regex test to allow leading and trailing whitespace (or not).
Or for a possibly slightly more readable but longer solution, try:
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?}