Find a component definition in a list
-
i select an object in the model
If it is a component, the code gets its definition and puts it in a string named "ref"for e in selection if e.is_a? Sketchup;;ComponentInstance ref = e.definition.name.to_s end endthen i want to compare the "ref" to strings in a list (an array?) called "references", and find the one that matches
for z in (0..715) do if references[z] == ref puts "hello" end endI know there is one string among the 716 strings, that matches to "ref", but the program never says "hello", doesn't find it
what am i missing? Is it a bug in Ruby?
-
Define 'ref' OUTSIDE of the block iteration
ref=nil for e in selection if e.is_a? Sketchup;;ComponentInstance ref = e.definition.name.to_s end endSome simpler code would be
ref=selection.grep(Sketchup;;ComponentInstance)[0] return nil unless refThen
references.each{|r| if ref==r puts 'hello' break end }OR MUCH simpler
puts 'hello' in references.include?(ref)Are you sure that the exact 'name' is in the array ?
What is 'ref' ?? -
@glro said:
what am i missing? Is it a bug in Ruby?
sorry for asking the question, i found the answer...
for z in (0..715) do #rstrip to suppress whitespaces if references[z].rstrip == ref puts "hello" end #if end #for z ini had whitespaces at the end of references[z]; to remove them:
52 str.rstrip
Returns a copy of str with trailing whitespace removed.funny how programming depends so much on very trivial details...
-
A less verbose version:.
<span class="syntaxdefault">result </span><span class="syntaxkeyword">= </span><span class="syntaxdefault">references</span><span class="syntaxkeyword">.</span><span class="syntaxdefault">find </span><span class="syntaxkeyword">{ |</span><span class="syntaxdefault">string</span><span class="syntaxkeyword">| </span><span class="syntaxdefault">string</span><span class="syntaxkeyword">.</span><span class="syntaxdefault">rstrip </span><span class="syntaxkeyword">== </span><span class="syntaxdefault">ref </span><span class="syntaxkeyword">}<br /></span><span class="syntaxdefault">puts </span><span class="syntaxstring">'Hello' </span><span class="syntaxkeyword">if </span><span class="syntaxdefault">result</span>
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