Sha256: ee50302a2d198e2681dd0a66564acce84cfe025c26e852afdee7a85a613c5049

Contents?: true

Size: 877 Bytes

Versions: 3

Compression:

Stored size: 877 Bytes

Contents

class Hash

  # Any array values will be replaced with the first element of the array.
  # Arrays with no elements will be set to nil.
  #
  #   h = { :a=>[1], :b=>[1,2], :c=>3, :d=>[] }
  #   h.dearray_values  #=> { :a=>1, :b=>1, :c=>3, :d=>nil }
  #
  # CREDIT: Trans

  def dearray_values(index=0)
    h = {}
    each do |k,v|
      case v
      when Array
        h[k] = v[index] || v[-1]
      else
        h[k] = v
      end
    end
    h
  end

  # Any array values with one or no elements will be set to the element
  # or nil.
  #
  #   h = { :a=>[1], :b=>[1,2], :c=>3, :d=>[] }
  #   h.dearray_singular_values  #=> { :a=>1, :b=>[1,2], :c=>3, :d=>nil }
  #
  # CREDIT: Trans

  def dearray_singular_values
    h = {}
    each do |k,v|
      case v
      when Array
        h[k] = (v.size < 2) ? v[0] : v
      else
        h[k] = v
      end
    end
    h
  end

end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
facets-glimmer-3.2.0 lib/core/facets/hash/dearray_values.rb
facets-3.1.0 lib/core/facets/hash/dearray_values.rb
facets-3.0.0 lib/core/facets/hash/dearray_values.rb