Auto add numbers in Ruby?
-
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+1to 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 theputsorprintfwith
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.
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better π
Register LoginAdvertisement