From: Robert Klemme Date: 2011-10-18T05:10:08+09:00 Subject: Re: Ruby functions to split numbers On Mon, Oct 17, 2011 at 7:48 PM, ideal one wrote: > Robert Klemme wrote in post #1026992: >> On Fri, Oct 14, 2011 at 11:54 PM, ideal one >> wrote: >>>> keep in mind that a number with a leading zero makes ruby think the base >>>> is >>>> octal: >>>> >>>> ruby-1.9.2-p290 :019 > 012 >>>> => 10 >>>> >>>> hope that helps. >> >>>       How can i auto increment the number, i tried doing >>> something like this... >>> var1 is always constant, but i want to autoincrement var2 >>> >>> value = var2 + 1 # iam getting Cannot convert Fixnum to String Error. >>> is something like this works var2++, not tried this in ruby. >>> Preserve leading Zero and also autoincrement.. >> >> I am still not sure I get what you really want to do with those >> numbers.  What exactly is your input (String or a Fixnum) and what do >> you want to do with it? >> >> Here is one more way to split and assign to local variables: >> >> irb(main):009:0> s = "1234567" >> => "1234567" >> irb(main):010:0> /\A(?\d{1,3})(?\d{5})\z/ =~ s >> => 0 >> irb(main):011:0> v1 >> => "12" >> irb(main):012:0> v2 >> => "34567" >> >> But if your input is already numeric other approaches are usually >> better, e.g. >> >> irb(main):013:0> n = 1234567 >> => 1234567 >> irb(main):014:0> v1 = n / 100000 >> => 12 >> irb(main):015:0> v2 = n % 100000 >> => 34567 >> >> (Assuming we're talking about decimal representation.) >> >> Kind regards >> >> robert > > Hi All, > >           Sorry if I am not clear with my requirement, Let me try to > explain in detail... > I have to create few Accounts, so the account number i am providing to > the system manually each time and it should be in series. > I have to enter the 7 digit account numbers in two text box in my > application. > the First 3 digits goes in first text box and remaining 4 digits goes in > the second text box, that is why i was looking for a Split function. > > eg:  Default or starting Account No - 1230567, so next one in series > should be 1230568,1230569....so on. I need to increment this account > number everytime, so that my code picks the next correct number. > Secondly, i have to place these account numbers in two different text > boxes. > first 3 digits, ie 123 goes into first text box > remaining 4 digits goes into second text box. > > Increment and Splitting the numbers in my code, the better way i was > looking for.... def split_account(no) high, low = no.to_int.divmod 10_000 ["%03d" % high, "%04d" % low] end 100.times do |num| a, b = split_account num # ... end or 123456.upto 123470 do |num| a, b = split_account num # ... end Instead of "" % x you can also use sprintf - it's the same. > Let me know if you require more information. Where do you need the leading zeros? Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/