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 end
then 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 end
I 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 end
Some simpler code would be
ref=selection.grep(Sketchup;;ComponentInstance)[0] return nil unless ref
Then
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 in
i had whitespaces at the end of references[z]; to remove them:
52 str.rstrip
Returns a copy of str with trailing whitespace removed.Ruby - Strings
Ruby - Strings - A String object in Ruby holds and manipulates an arbitrary sequence of one or more bytes, typically representing characters that represent human language.
(www.tutorialspoint.com)
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>
Advertisement