Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In your specific case, you can calculate the divisor. See <a href="https://stackoverflow.com/a/14495597/676874">Dnyans answer</a>.</p> <p>If you have a similar problem and you can't calculate the result, but want to avoid the <code>if</code>-<code>elsif</code> structure, then you could use <code>case</code>:</p> <pre><code>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 </code></pre> <p>To implement the <code>&lt; 100</code> is a bit <a href="https://stackoverflow.com/questions/5778295/how-to-express-infinity-in-ruby">more complex</a>:</p> <pre><code>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 </code></pre> <p>If you want to avoid to assign <code>divisor</code> each time, you could use the result of the <code>case</code>-command:</p> <pre><code>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 </code></pre> <p>And combined with <a href="https://stackoverflow.com/a/14496809/676874">sawas answer</a> you can make it for all values:</p> <pre><code>divisor = case number when 0...100 10 when 100...1000 100 else (10 ** (Math.log10(number).to_i / 3 * 3)) end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload