color icon indicating copy to clipboard operation
color copied to clipboard

Suggestion: Make Color::RGB#name available for value-created colors

Open akicho8 opened this issue 2 months ago • 0 comments

Thank you very much for creating such a useful library. I’ve been using it since version 1, and I really appreciated that you personally announced the breaking changes when version 2 was released. The new version has a beautifully clean design, and reading the source code has been very educational for me.

While using the latest version, I encountered a small point of confusion that I’d like to share. This is just an idea for consideration, not a strong request.

require "color"
Color::VERSION                  # => "2.1.1"

# I was a bit confused when I noticed that even though these two objects represent the same color, only one of them has a color name:

a = Color::RGB.by_hex("#ff0000") # => RGB [#ff0000]
b = Color::RGB[1.0, 0.0, 0.0]    # => RGB [#ff0000]
a == b                           # => true

a.name                           # => "red"
b.name                           # => nil

# It might be helpful if name also worked for colors created by value, for example:

Color::RGB.class_eval do
  def name
    names&.first || self.class.send(:__by_hex)[hex]&.name
  end
end

b.name                           # => "red"

# Also, it might be nice if the inspect output made it easier to tell whether an object is a value object or one created from the color showcase, for example:

Color::RGB.class_eval do
  def inspect
    "RGB [#{html}] #{names}".strip
  end
end

a                               # => RGB [#ff0000] ["red"]
b                               # => RGB [#ff0000]

akicho8 avatar Nov 03 '25 06:11 akicho8