Send true only once if one or more components are present in a selection!

Hello

It’s been almost two years since I stopped my apprenticeship in Ruby and today I want to resume.
I am a beginner so please be lenient with me.

I want to send a window with a message only once if one or more components are present in my selection.

mod = Sketchup.active_model
sel = mod.selection
sel.each do |s| 
  if s.is_a? Sketchup::ComponentInstance 
    UI.messagebox("A component and present in the selection!")
  else
    UI.messagebox("No component is present in your selection!")
  end
end

This method works but the problem is that it sends the message several times if several components are in my selection.

So how can I send the message only once even if several components are in my selection?

Thank you in advance for your help.

e.g.:

mod = Sketchup.active_model
sel = mod.selection
# Array of instances or empty Array
instances = sel.grep(Sketchup::ComponentInstance) 
if instances.size > 0
  UI.messagebox("#{instances.size}  component(s) present in the selection!")
else
  UI.messagebox("No component is present in your selection!")
end

Thanks dezmo for this method which works perfectly with the components!

Another case
If for example we have an array:

array = ["A0","B0","C0","B1","A2","C1","A3"]
array.each do |a|
  if a.include? ("A")
    p "YES"
  end    
end

How to send “YES” only once if the character “A” is found?

Thank you

p "YES" if array.any? {|item| item =~ /^A/ }

… OR …

p "YES" if array.any? {|item| item.start_with?("A") }

REF:

1 Like

e.g.

array = ["A0","B0","C0","B1","A2","C1","A3"]
p "Yes" if array.any?{|text| text.include?("A")}
1 Like

Great, there are several methods.
Thank you for your answers. :grinning:

Last little questions.

1.How to send no if “A” is not found.

2.Can you lay the code in the form of a method like in my example and not in a single line?
Because I am not yet able to transform a one-line code into a method with def and end.

3.How do you call the one-line code and the code with def and end?

Thanks for your help.

def ary_include_char( array, chr )
  if array.any?{|text| text.include?( chr )}
    return "YES"
  else
    return "NO"
  end
end

#call the method e.g:
ary_include_char(["A0","B0","C0","B1","A2","C1","A3"], "A") # => YES
ary_include_char(["A0","B0","C0","B1","A2","C1","A3"], "X") # => NO

Start e.g. here:
https://developer.sketchup.com/developers/welcome

Thank you very much for your help and links.
The solution was not so easy for a beginner like me because your method works with arrays and attributes in the definitions.