Auto add numbers in Ruby?
-
I've forgotten how to do this the quick way (seem like there is a method already set up nicely for what I want).
I want to take a string and add numbers to the beginning of it.
Chris
Dan
Jim
Martin
Thombecomes
0001Chris
0002Dan
0003Jim
0004Martin
0005ThomSeems like there is a method I can use that does this automatically and smoothly for me, where I should be able to specify the amount of placeholders to use (in the example I show 4 10's places being held). Anyone recall what I'm thinking of? Just hte method is enough, I can look up its syntax again if you could kindly point me in the right direction. Thanks,
Chris
-
The easiest is to use strings and
.next
."0000".next => "0001"
Otherwise, if you use numbers you need to use
printf
orsprintf
(aka format).10.times { |i| printf "%04d\n", i }
names = %w( Joe Mike Tim ) names.each_with_index do |name, i| printf "%04d%s\n" % [i, name] end
See sprintf for details on formatting.
-
Awesome, thanks Jim. It was string.next that I was trying to think of. That is all I needed, thanks again!
Chris
a = "000" 10.times do puts a a = a.next end
-
Another way is:
'1'.rjust(4, '0')
-
You don't have to do this:
a = a.next
- you can instead doa.next!
. Most probably that will be faster - thought not noticeable until you run many iterations.If you did not require '0000' then you could also do:
a = '0000' 10.times{ puts a.next! }
-
Ahh, good idea on the next! method. It didn't cross my mind that it might exist. I also like that rjust method. I'll look into that one too. Thanks Thom,
Chris
-
-
Laughing at my inability to express myself in functional english there Todd , or is there a big inside joke I missed (both equally likely).
Chris
-
@jim said:
> names = %w( Joe Mike Tim ) > names.each_with_index do |name, i| > printf "%04d%s\n" % [i, name] > end >
index starts at 0, you'd need
i+1
to start at 1also..
printf "%04d%s\n" % [i, name]
is adding an extra operation eval that's not needed.
could be either:
puts "%04d%s\n" % [i+1, name]
or
printf("%04d%s\n",i+1,name)
-
Of course if your wanting to build up an Array of Hash keys (or Attribute Dictionary keys,) just create an empty array first
keys=[]
then replace theputs
orprintf
with
keys.push
-
@chris fullmer said:
Laughing at my inability to express myself in functional english there Todd , or is there a big inside joke I missed (both equally likely).
Chris
The first.
-
@dan rathbun said:
also.. printf "%04d%s\n" % [i, name]
is adding an extra operation eval that's not needed.Note to self:
%
is a method of Strings. Thanks.
Advertisement