Skip to content

Commit c6d8a30

Browse files
committed
More improvements
- Require at least Ruby 3 so we can use Symbol#name - Use case/when for faster type dispatch - Reduce calls to #to_s - Use #each_value instead of #each and getting the value
1 parent 6ce7172 commit c6d8a30

2 files changed

Lines changed: 21 additions & 14 deletions

File tree

hash_kit.gemspec

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ Gem::Specification.new do |spec|
2020
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
2121
spec.require_paths = ['lib']
2222

23+
spec.required_ruby_version = '>= 3.0.0'
24+
2325
spec.add_development_dependency 'benchmark-ips', '~> 2.0'
2426
spec.add_development_dependency 'bundler'
2527
spec.add_development_dependency 'pry'

lib/hash_kit/helper.rb

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,17 @@ module HashKit
44
# Hash kit Helper class
55
class Helper
66
INDIFFERENT_PROC = proc do |h, k|
7-
if h.key?(k.to_s)
8-
h[k.to_s]
9-
elsif h.key?(k.to_sym)
10-
h[k.to_sym]
7+
case k
8+
when Symbol
9+
# Symbol#name returns a frozen string without allocating (Ruby 3.0+)
10+
str = k.name
11+
h[str] if h.key?(str)
12+
when String
13+
sym = k.to_sym
14+
h[sym] if h.key?(sym)
1115
else
12-
nil
16+
str = k.to_s
17+
h[str] # returns nil on miss
1318
end
1419
end
1520

@@ -23,13 +28,12 @@ def indifferent!(hash)
2328
hash.default_proc = INDIFFERENT_PROC
2429

2530
# Recursively process any child hashes
26-
hash.each do |key,value|
27-
unless hash[key].nil?
28-
if hash[key].is_a?(Hash)
29-
indifferent!(hash[key])
30-
elsif hash[key].is_a?(Array)
31-
indifferent_array!(hash[key])
32-
end
31+
hash.each_value do |value|
32+
case value
33+
when Hash
34+
indifferent!(value)
35+
when Array
36+
indifferent_array!(value)
3337
end
3438
end
3539

@@ -40,9 +44,10 @@ def indifferent_array!(array)
4044
return unless array.is_a?(Array)
4145

4246
array.each do |i|
43-
if i.is_a?(Hash)
47+
case i
48+
when Hash
4449
indifferent!(i)
45-
elsif i.is_a?(Array)
50+
when Array
4651
indifferent_array!(i)
4752
end
4853
end

0 commit comments

Comments
 (0)