How do I raise a number in a loop?
-
I want to loop through an array and apply an attribute to each item starting with 000001 and raise it by one for next item.
I don't want 1....2...10....90000 but 000001...000002...000010...090000.
How do I do that? -
If you use a number, the leading zeroes may get stripped. But you can use the
.next!
method on a String.att = "0000" ary.each { |item| item.set_attribute("Dict Name", att) att.next! }
-
Thanks, will try this.
-
Pixero,
Of course what Jim suggest is correct but I'd think carefully here.
You want to try and keep attributes as small (memory-wise) as possible because there can be many Entities you are going to attach attributes to - so think of it as the ID "value" and the formatting of the ID as being two different problems.
I'd suggest you store an integer attribute, but when you print them out / compare them / whatever, turn them into your leading-zero format.
That way, your model file will be smaller and you're free to change the formatting (eg add an extra zero) at a later date.
Adam
-
Ok, that make sence.
Following Jims example would it be something like:att = 0 ary.each { |item| item.set_attribute("Dict Name", att) att+=1 }
-
@pixero said:
Ok, that make sence.
Following Jims example would it be something like:att = 0 > ary.each { |item| > item.set_attribute("Dict Name", att) > att+=1 > }
1) There's a parameter missing in set_attribute, the 3rd arg is the value argument to assign to the attribute. (Would the example assign nil, or would an ArgumentError be raised?)
2) The examples will begin at 0, not 1. (You could adjust the start ordinal for var att in it's assignment statement.)
3) Be sure the array is sorted first the way you wish to have the attributes numbered. You may need to write your own sort method if the objects in the array are complex objects, such as Drawingelement subclasses. Meaning you may wish to sort by some property of the object, such as it's height above the XY plane (just as an example.)
4) Whenever you need to iterate an enumerble Ruby object, you can use the each_with_index method (that is inherited from the "mixin" module Enumerable.)
Here I add 1 to the index, so the numbering starts at 1:dict = "My Dictionary Name" val = "some value" ary.each_with_index { |item,pos| item.set_attribute( dict, pos+1, val ) }
If you still wish to use 0 padded string attribute names:
dict = "My Dictionary Name" val = "some value" places = 6 ary.each_with_index { |item,pos| item.set_attribute( dict, (pos+1).to_s.rjust(places,'0'), val ) }
Note: The 2nd arg in rjust, the padstring, is optional and defaults to a space character.
Advertisement