Class: Hash

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

Instance Method Summary collapse

Instance Method Details

#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)


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

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:



77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/everythingrb/core/hash.rb', line 77

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)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/everythingrb/core/hash.rb', line 57

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