pankajdoharey
pankajdoharey

Reputation: 1572

Can there be a better method than condition checking ? would switch be more efficient?

if i have to produce a result like this:

0001
0002
.
.
.
0099
0100
.
.
0184

for i in 1..184
    a = i.to_s
    if a.length == 1
        puts "000"+ a
    elsif a.length == 2
        puts "00"+ a
    else
        puts "0"+ a
    end
end

can there be a better and more efficient method than this instead of so much condition checking ?

Upvotes: 1

Views: 63

Answers (1)

Adam Eberlin
Adam Eberlin

Reputation: 14205

So you want to zero-pad an integer?

184.times{ |n| puts "%04d" % (n + 1) }

Upvotes: 4

Related Questions