Sha256: 085a08f961a0c8c55ee74bea33ad9a47ee8a5cf6e806883b1bfad1c419ee41ff

Contents?: true

Size: 976 Bytes

Versions: 1

Compression:

Stored size: 976 Bytes

Contents

# frozen_string_literal: true

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'

  gem 'u-struct', path: '..'
end

RGBColor = Micro::Struct.with(:readonly, :to_ary).new(:red, :green, :blue) do
  Number = ->(value) do
    return value if value.is_a?(::Integer) && value >= 0 && value <= 255

    raise TypeError, "#{value} must be an Integer(>= 0 and <= 255)"
  end

  def initialize(r, g, b)
    super(Number[r], Number[g], Number[b])
  end

  def to_hex
    '#%02x%02x%02x' % self
  end
end

puts

rgb_color = RGBColor.new(red: 1, green: 1, blue: 255)

p rgb_color

puts
puts format('to_a: %p', rgb_color.to_a)
puts format('to_hex: %p', rgb_color.to_hex)
puts

r, g, b = rgb_color

puts format('red: %p', r)
puts format('green: %p', g)
puts format('blue: %p', b)
puts

*rgb = rgb_color

puts rgb.inspect
puts

begin
  RGBColor.new(red: 1, green: -1, blue: 255)
rescue => exception
  puts exception # TypeError (-1 must be an Integer(>= 0 and <= 255))
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
u-struct-1.0.0 examples/rgb_1.rb