Skip to content

Commit 1ee2c8b

Browse files
committed
Adds #unshift to hash
Hash#shift removes the first key-value pair, returning them as an array ex. ``` {item: "Hot Dog", price: 3.5, denomination: "USD"}.shift [:item, "Hot Dog"] ``` Ruby includes no #unshift for hashes (although it does for Arrays) which is unfair. This PR adds Hash#unshift which takes a key-value pair as an array and adds it to the hash in the "beginning" position: ex. ``` {price: 3.5, denomination: "USD"}.unshift [:item, "Hot Dog"] {item: "Hot Dog", price: 3.5, denomination: "USD"} ```
1 parent 30b32aa commit 1ee2c8b

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/pretty_ruby.rb

+12
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,18 @@ def partial_seqs
176176

177177
end
178178

179+
refine Hash do
180+
def unshift(key_val_pair)
181+
key = key_val_pair[0]
182+
val = key_val_pair[1]
183+
old = self.dup
184+
self.clear
185+
self[key] = val
186+
self.merge! old
187+
return self
188+
end
189+
end
190+
179191
#TODO: add separate tests for this
180192
refine ::Enumerable do
181193

test/pretty_ruby_test.rb

+23
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,29 @@
225225

226226
end
227227

228+
describe 'Hash' do
229+
before do
230+
@hash = {item: 'Hot Dog', price: 3.5, denomination: 'USD'}
231+
end
232+
233+
describe "without refinement" do
234+
235+
describe "#unshift" do
236+
it "raises" do
237+
->() { @hash.unshift [:condiment, 'mustard'] }.must_raise NoMethodError
238+
end
239+
end
240+
end
241+
242+
using PrettyRuby
243+
244+
describe "#unshift" do
245+
it 'adds a key-value pair to the "beginning" of a hash' do
246+
@hash.unshift([:condiment, 'mustard']).must_equal({condiment: 'mustard', item: 'Hot Dog', price: 3.5, denomination: 'USD'})
247+
# @hash.unshift([:condiment, 'mustard']).must_equal([:condiment, 'mustard'])
248+
end
249+
end
250+
end
228251
__END__
229252

230253
refine Enumerable do

0 commit comments

Comments
 (0)