I want to get the material of the selected entities

this is my command by it’s giving error

Sketchup.active_model.selection.entities.materials.map{|x| x.name}

but this command is giving materials of all the models

Sketchup.active_model.materials.map{|x| x.name}

What error does it give you? The error usually tells you what is wrong, or at least a hint.

NoMethodError: undefined method `entities' for #<Sketchup::Selection:0x00000014a787f8>

That means the return value of the method selection does not have a method entities.

  1. Find out what is the type of the return value of the last method that works. It’s a Sketchup::Selection
  2. Lookup which methods an object of that type supports: https://ruby.sketchup.com/Sketchup/Selection.html
    There is no entities.
  3. Find an alternative method to achieve what you want.
    • Selection is an enumerable, that means it works like a list or array (you can look into the contained entities by converting it to an array). Try to_a and see the result.
    • To list all methods that an object supports, use methods:
    • materials is a method either of the whole model or of an individual drawing element. That means you need to iterate over entities and call material on each individual entity.
    • You can apply map on the selection and material on each drawing element. You notice some drawing elements have no material (nil), so you apply name only when the material is not nil.
    • With compact you can remove nil from an array.
    • map(&:method_name) is a shortcut for map{|x| x.method_name() } for methods without arguments.