2016-11-23 22 views
-4

0から9までの数字を含む文字列を指定して整数を出力する方法はありますか?たとえば、入力は「219」、出力は219となります。Ruby文字列を.to_iなしで整数に変換する方法

+3

「to_i」を使用できないのはなぜですか? –

+0

@muistooshortそれはホワイトボードの質問です、それは挑戦です。 – morrime

+0

他の人に仕事をさせてもらうことは難しいことではありません。 –

答えて

2

に.to_i使用あなたはKernel::Integerを使用することができます。

Integer("219") 
    #=> 219 
Integer("21cat9") 
    # ArgumentError: invalid value for Integer(): "21cat9" 

次のように時には、この方法が使用されている:それはあまり選択的であるものの

def convert_to_i(str) 
    begin 
    Integer(str) 
    rescue ArgumentError 
    nil 
    end 
end 

convert_to_i("219") 
    #=> 219 
convert_to_i("21cat9") 
    #=> nil 
convert_to_i("1_234") 
    #=> 1234 
convert_to_i(" 12 ") 
    #=> 12 
convert_to_i("0b11011") # binary representation 
    #=> 27 
convert_to_i("054")  # octal representation 
    #=> 44 
convert_to_i("0xC")  # hexidecimal representation 
    #=> 12 

は、いくつかはそれとして、( "インライン救助" を使用します救助すべての例外):

def convert_to_i(str) 
    Integer(str) rescue nil 
end 

文字列を浮動小数点または有理数に変換する類似のカーネルメソッドがあります。

+0

整数( "0054") => 44 – morrime

+1

@morrimeは整数( "0054"、10) 'になります。 @Caryが –

+1

にリンクしているドキュメントを読む "007"では動作しますが、 "008"では動作しません。これは、8進数7(07)が10進数7と同じで、Integer( "008")#=> ArgumentError:Integer()の値が "008"であるためです。 @luka、良い点。 –

-1
def str_to_int(string) 
digit_hash = {"0" => 0, "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9} 
total = 0 
num_array = string.split("").reverse 
num_array.length.times do |i| 
    num_value = digit_hash[num_array[i]] 
    num_value_base_ten = num_value * (10**i) 
    total += num_value_base_ten 
end 
return total 
end 

puts str_to_int("119") # => 119 
+0

負の整数を忘れないでください。 –

+0

@CarySwovel私はそれを以前に言及しておきましたが、ホワイトボードの問題のパラメータは文字列が0-9の文字だけであるため、ネガティブは不可能だと言います。 – morrime

+1

ハッシュの代わりに 'num_array [i] .ord - 48'があります。 [Enumerable#reduce](http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-reduce)(別名 'inject')と[Array#reverse_each](http: /ruby-doc.org/core-2.3.0/Array.html#method-i-reverse_each): 'str =" 123 "; fac = 1; str.chars.reverse_each.reduce(0)do | tot、digit |; tot + =(digit.ord - 48)* fac; fac * = 10; tot;終わり。 –

関連する問題