Adding suffix or prefix to instance name for multiple components

Hi all,

Total newbie here. I am hoping to write a script/extension that allows me to add a suffix or pre-fix to the instance name of a bunch of components. I would want to select a bunch of components (some of which will be repeated instances of the same component, others not) then change their instance name to have a suffix or prefix. For example:

Original component instance: Component1
New component instance: Prefix_Component1_Suffix

Can someone point me in the direction of how to do this?

Chris

You need to understand the difference between a component-definition and its component-instances.
Instances are not automatically named, but you might have done this manually or in other API code…
So for now let’s assume you have a reference to a definition named 'Component1' and you want to add this with a prefix and/or suffix [which we’ll assume your have referenced these by those variable-names], to then use as an instance’s name…
instance.name = "#{prefix}_#{definition.name}_#{suffix}"
If you want to increment the suffix etc, as you process a number of instances, then use suffix.next! before the next one is named in the iteration block…

EDIT: fixed code which I’d quickly typed without testing…
Dan’s code is correct and probably more practical !

1 Like

Thanks very much @TIG . I’m aware of the difference between definition and instances- I confused thing by using “Component 1” as the instant name!

This is really helpful, thanks!

String interpolation uses #{ … } delimiters within double quoted strings. Ie …

instance.name = "#{prefix}_#{definition.name}_#{suffix}"
selection.each do |instance|
  instance.name = "#{prefix}_#{instance.definition.name}_#{suffix}"
end
1 Like

Hi all,

Thanks for your help so far. I put the below into the Ruby console. Any reason this doesn’t work? I can get it to work if I first enter prefix=“WT01”, then separately execute the rest of the code.

prefix= “WT01”
model = Sketchup.active_model
selection = model.selection
selection.each do |instance|
instance.name = “#{prefix}_#{instance.name}”
end

Please read this how to post your code properly:


We will understand better your problem, if you also include what Error message you see on Ruby Console when you are executing your code.


I assuming a syntax problem in your code: perhaps you are using quotation marks which is not the right one…

Does this work if I copy-paste it?

prefix= "WT01"
model = Sketchup.active_model
selection = model.selection
selection.each do |instance|
  instance.name = "#{prefix}_#{instance.name}"
end
2 Likes

Yes that works! I think I didn’t post code properly.