有没有办法在给定包含0到9之间的数字的字符串的情况下输出整数。例如,输入为“219”,输出为219,您不能使用.to_i
答案 0 :(得分:2)
您可以使用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
有类似的内核方法可以将字符串转换为float或rational。
答案 1 :(得分:0)
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