说我有一个像哈希:获取来自哈希数字键红宝石
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
这将返回的值是整数(正或负)的键。