Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/everythingrb/core/hash.rb

Instance Method Summary collapse

Instance Method Details

#deep_freezeself

Recursively freezes self and all of its values

Examples:

Freeze a hash with nested structures

{ user: { name: "Alice", roles: ["admin"] } }.deep_freeze
# => Hash and all nested structures are now frozen

Returns:

  • (self)

    Returns the frozen hash



98
99
100
101
# File 'lib/everythingrb/core/hash.rb', line 98

def deep_freeze
  each_value { |v| v.respond_to?(:deep_freeze) ? v.deep_freeze : v.freeze }
  freeze
end

#join_map(join_with = "") {|Object| ... } ⇒ String

Combines filter_map and join operations

Examples:

{ a: 1, b: 2, c: nil, d: 3 }.join_map(" ") { |v| v&.to_s if v&.odd? }
# => "1 3"
{ a: 1, b: 2, c: nil, d: 3 }.join_map(", ")
# => "a, 2, b, 2, c, d, 3"

Parameters:

  • join_with (String) (defaults to: "")

    The delimiter to join elements with (defaults to empty string)

Yields:

  • (Object)

    Block that filters and transforms hash values

Returns:

  • (String)

    Joined string of filtered and transformed values

See Also:



23
24
25
26
27
# File 'lib/everythingrb/core/hash.rb', line 23

def join_map(join_with = "", &block)
  block = ->(kv_pair) { kv_pair.compact } if block.nil?

  filter_map(&block).join(join_with)
end

#to_istructData

Converts hash to an immutable Data structure

Returns:

  • (Data)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/everythingrb/core/hash.rb', line 34

def to_istruct
  recurse = lambda do |input|
    case input
    when Hash
      input.to_istruct
    when Array
      input.map(&recurse)
    else
      input
    end
  end

  Data.define(*keys.map(&:to_sym)).new(*values.map { |value| recurse.call(value) })
end

#to_ostructOpenStruct

Converts hash to an OpenStruct recursively

Returns:



74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/everythingrb/core/hash.rb', line 74

def to_ostruct
  recurse = lambda do |value|
    case value
    when Hash
      value.to_ostruct
    when Array
      value.map(&recurse)
    else
      value
    end
  end

  OpenStruct.new(**transform_values { |value| recurse.call(value) })
end

#to_structStruct

Converts hash to a Struct recursively

Returns:

  • (Struct)


54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/everythingrb/core/hash.rb', line 54

def to_struct
  recurse = lambda do |value|
    case value
    when Hash
      value.to_struct
    when Array
      value.map(&recurse)
    else
      value
    end
  end

  Struct.new(*keys.map(&:to_sym)).new(*values.map { |value| recurse.call(value) })
end