From: Jeremy Bopp Date: 2011-10-15T04:07:35+09:00 Subject: Re: Ruby functions to split numbers On 10/14/2011 13:52, ideal one wrote: > HI All, > I have couple of requirements to be handled in ruby, it will be > great if anyone can shed some light on this. > > 1) i have a 8 digit number, to be used in my code as 2 parts(split), > like shown below. > > Number = "34502305" # I put them in double quotes, so that leading > zeros are preserved. > Var1 = 345 # split firs 3 digits always > Var2 = 02305 # split remaining digits with preserving leading Zero if > it exists > > i tried doing something like this, not sure if its correct > > sprintf("%2d", number) > > I am not able to preserve leading zero or i get fixnum to string error How do you want to work with your numbers within your program? Do you want them to be real numbers or strings? As numbers, you would need to tell sprintf how large the resulting string should be and with what to pad the string in case the number is too short to fill the field. It's a bit long, but the documentation for sprintf should help you with the details. Come back if you have a specific question about sprintf itself: http://rdoc.info/stdlib/core/1.9.2/Kernel:sprintf Check out what this does: sprintf("%010d", 1234567) If you want to work with the numbers as strings in your program, you don't need to use the sprintf method at all since they will already be strings with the necessary padding, assuming Number (from your example) is sufficiently padded and your splitting process avoids dropping anything. -Jeremy