Method: Hanami::Utils::Kernel.Set

Defined in:
lib/hanami/utils/kernel.rb

.Set(arg) ⇒ Set

Coerces the argument to be a Set.

Examples:

Basic Usage

require 'hanami/utils/kernel'

Hanami::Utils::Kernel.Set(nil)              # => #<Set: {}>
Hanami::Utils::Kernel.Set(true)             # => #<Set: {true}>
Hanami::Utils::Kernel.Set(false)            # => #<Set: {false}>
Hanami::Utils::Kernel.Set(1)                # => #<Set: {1}>
Hanami::Utils::Kernel.Set([1])              # => #<Set: {1}>
Hanami::Utils::Kernel.Set([1, 1])           # => #<Set: {1}>
Hanami::Utils::Kernel.Set([1, [2]])         # => #<Set: {1, [2]}>
Hanami::Utils::Kernel.Set([1, [2, nil]])    # => #<Set: {1, [2, nil]}>
Hanami::Utils::Kernel.Set({a: 1})           # => #<Set: {[:a, 1]}>

Set Interface

require 'securerandom'
require 'hanami/utils/kernel'

UuidSet = Class.new do
  def initialize(*uuids)
    @uuids = uuids
  end

  def to_set
    Set.new.tap do |set|
      @uuids.each {|uuid| set.add(uuid) }
    end
  end
end

uuids = UuidSet.new(SecureRandom.uuid)
Hanami::Utils::Kernel.Set(uuids)
  # => #<Set: {"daa798b4-630c-4e11-b29d-92f0b1c7d075"}>

Unchecked Exceptions

require 'hanami/utils/kernel'

Hanami::Utils::Kernel.Set(BasicObject.new) # => TypeError

Parameters:

  • arg (Object)

    the input

Returns:

  • (Set)

    the result of the coercion

Raises:

  • (TypeError)

    if arg doesn’t implement #respond_to?

Since:

  • 0.1.1


150
151
152
153
154
155
156
157
158
# File 'lib/hanami/utils/kernel.rb', line 150

def self.Set(arg)
  if arg.respond_to?(:to_set)
    arg.to_set
  else
    Set.new(::Kernel.Array(arg))
  end
rescue NoMethodError
  raise TypeError.new("can't convert #{inspect_type_error(arg)}into Set")
end