Module: HashModernInspect

Defined in:
lib/hash_modern_inspect.rb

Instance Method Summary collapse

Instance Method Details

#modern_inspectObject



2
3
4
# File 'lib/hash_modern_inspect.rb', line 2

def modern_inspect
  modern_inspect0(self)
end

#modern_inspect0(obj) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/hash_modern_inspect.rb', line 14

def modern_inspect0(obj)
  buf = ''

  case obj
  when Array
    buf << '['

    obj.each_with_index do |value, i|
      buf << ', ' unless i.zero?
      buf << modern_inspect0(value)
    end

    buf << ']'
  when Hash
    buf << '{'

    obj.each_with_index do |kv, i|
      key, value = kv
      buf << ', ' unless i.zero?

      if key.is_a?(Symbol)
        key = key.to_s

        if key =~ /\A\w+\z/
          buf << "#{key}: "
        else
          buf << "#{key.to_s.inspect}: "
        end
      else
        buf << "#{modern_inspect0(key)}=>"
      end

      buf << modern_inspect0(value)
    end

    buf << '}'
  else
    buf << obj.inspect
  end

  buf
end

#modern_inspect_without_brace(options = {}) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/hash_modern_inspect.rb', line 6

def modern_inspect_without_brace(options = {})
  if self.empty? and not options[:allow_empty]
    self.inspect
  else
    modern_inspect.sub(/\A\{/, '').sub(/\}\z/, '').strip
  end
end