私はいつもKernel::Integerを使用し、それが整数の文字列表現である場合にのみや、文字列を整数に変換したい:ここ
arr = ["3", "a", "2", "0x01", "0c", "0b11", "0o03", "4", "1_000"]
arr.select { |s| Integer(s) rescue nil }.min_by { |s| Integer(s) }
#=> "0x01"
arr.select { |s| Integer(s) rescue nil }
#=> ["3", "2", "0x01", "0b11", "0o03", "4", "1_000"]
注意"0x01".to_i #=> 0
(そうではないので、Integer
を2回使用する必要があります)。
ストリングが整数の表現ではない場合、Integer
は、例外を発生させる:
インライン救出さ
Integer("a")
#=> ArgumentError: invalid value for Integer(): "a"
、nil
が選択されていない文字列であり、結果として返されるせます。 (もちろん、余分な距離を移動して、ArguementError
例外を救う句を使用することもできます)
質問は、配列の要素(文字列)が返されるかどうか尋ねます。その整数同等を希望する場合は、次のように記述することができます:
我々は次の操作を行うと、冗長な-文字列除外することができます
Enumerable#grep_v使用
a = arr.map { |s| Integer(s) rescue nil }.compact.min
#=> 1
arr.map { |s| Integer(s) rescue nil }
#=> [3, nil, 2, 1, nil, 3, 3, 4, 1_000]
注
['a', 'b'].map { |s| Integer(s) rescue nil }.compact.min
#=> nil
@steenslagこのデータが肯定的であるかどうかは明らかではありませんでしたが、いずれにしてもオプションの '-'が追加されました。 – tadman