如何简化这段代码?

时间:2013-01-24 06:49:52

标签: ruby

如何简化这段代码?

if number < 100
    divisor = 10
elsif number < 1000
    divisor = 100
elsif number < 1000000 # 1 million
    divisor = 1000
elsif number < 1000000000 # 1 billion
    divisor = 1000000
elsif number < 1000000000000 # 1 trillion
    divisor = 1000000000
# Keep goin...
end

这里的重点是......

  • 如果号码为>= 0< 100我需要divisor = 10
  • 如果号码为>= 100< 1.000我需要divisor = 100
  • 如果号码为>= 1.000< 1.000.000我需要divisor = 1.000
  • 如果号码为>= 1.000.000< 1.000.000.000我需要divisor = 1.000.000
  • 这永远都在继续......

我尝试了whilepow的几种组合,但我没有在这里得到这种模式。

4 个答案:

答案 0 :(得分:3)

def divisor num
  10 ** (num < 1000 ? Math.log10(num).to_i : Math.log10(num).to_i / 3 * 3)
end

divisor(99) # => 10
divisor(999) # => 100
divisor(999_999) # => 1_000
divisor(999_999_999) # => 1_000_000
divisor(999_999_999_999) # => 1_000_000_000

或者,更紧凑:

def divisor num
  ->a{10 ** (a < 3 ? a : a / 3 * 3)}.call(Math.log10(num).to_i)
end

答案 1 :(得分:1)

尝试

   divisior = 10**(number.to_s.length - 1)

根据给定的条件
它会给你结果。

答案 2 :(得分:0)

在您的具体情况下,您可以计算除数。请参阅Dnyans answer

如果您遇到类似问题并且无法计算结果,但又想避开if - elsif结构,则可以使用case

case number 
  when 0...100
    divisor = 10
  when 100...1000
    divisor = 100
  when 1000...1000000 # 1 million
    divisor = 1000
  when 1000000...1000000000 # 1 billion
    divisor = 1000000
  when 1000000000...1000000000000 # 1 trillion
    divisor = 1000000000
# Keep goin...
  else
end

实施< 100有点more complex

NegativeInfinity = -1.0/0.0 
case number 
  when NegativeInfinity...100
    divisor = 10
  when 100...1000
    divisor = 100
  when 1000...1000000 # 1 million
    divisor = 1000
  when 1000000...1000000000 # 1 billion
    divisor = 1000000
  when 1000000000...1000000000000 # 1 trillion
    divisor = 1000000000
# Keep goin...
  else
end

如果您想避免每次分配divisor,可以使用case - 命令的结果:

divisor = case number 
  when NegativeInfinity...100
    10
  when 100...1000
    100
  when 1000...1000000 # 1 million
    1000
  when 1000000...1000000000 # 1 billion
    1000000
  when 1000000000...1000000000000 # 1 trillion
    1000000000
# Keep goin...
  else
end

结合sawas answer,您可以为所有值设置:

divisor = case number 
  when 0...100
    10
  when 100...1000
    100
  else
    (10 ** (Math.log10(number).to_i / 3 * 3))
end

答案 3 :(得分:0)

x=number
divisor=10
(x/=10;divisor*=10) while x>=100