2

如何简化这段代码?

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.
  • 这一直持续下去..

我尝试了一些 and 的组合whilepow但我没有在这里得到模式。

4

4 回答 4

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
于 2013-01-24T08:24:34.893 回答
1

尝试

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

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

于 2013-01-24T06:58:12.497 回答
0

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

如果您有类似的问题并且无法计算结果,但想避免使用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有点复杂

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-command 的结果:

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 答案,您可以使其适用于所有值:

divisor = case number 
  when 0...100
    10
  when 100...1000
    100
  else
    (10 ** (Math.log10(number).to_i / 3 * 3))
end
于 2013-01-24T08:40:00.280 回答
0
x=number
divisor=10
(x/=10;divisor*=10) while x>=100
于 2013-01-24T08:51:37.947 回答