Ruby: can the following array be generated with a one-liner using the step function: [1, 10, 100, 1_000, 10_000, 100_000, 1_000_000] -


i have thought of couple of different ways generate following array: [1, 10, 100, 1_000, 10_000, 100_000, 1_000_000]

it seems might possible generate array step function in elegant manner, not able figure out. passes in second argument step function , says want last value times 10:

0.step(1_000_000, ???).to_a 

here solutions have come far:

i don't inject solution because prefer specify 1_000_000 upper bound:

(0..6).inject([]) { |memo, number| memo << 10**number; memo } 

this ugly step solution came with:

result = [] 0.step(6) {|number| result << 10 ** number} result 

a while loop not feel right either, @ least lets me specify upper_bound (instead of math.log10(upper_bound)):

result = [1] while result.last < 1_000_000   result << result.last * 10 end result 

thanks help.

how this?

0.upto(math.log10(1_000_000)).map { |i| 10**i } 

it's going work powers of 10, lets specify upper bound, , computes powers of 10 iterate through.

if want lead upper bound, can via:

math.log10(10_000_000).to_i.downto(0).map {|i| 10 ** }.reverse 

if terseness important, can reopen fixnum generalized solution:

class fixnum   def by_powers_of(base = 10)     0.upto(math.log(self, base)).map {|i| base ** }   end end  10_000_000.by_powers_of(10) # => [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000]  (64**2).by_powers_of(2) # => [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096] 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -