ruby - Deal with Array of Hashes or single Hash ( from an API Response) -
i have api responding either:
an array of hashes
results = [{a: 1, b: 2}, {a:2, b:3}]
a single hash, if 1 result
results = {a:1, b:2}
or
nil
i'm trying work out elegant way deal situation can add parameter it's present.
e.g. situation 1:
results.map!{|h| h.update(c:3) }
situation 2:
results[:c] = 3
situation 3:
(don't anything)
i've tried
if results.is_a?(array) results.map!{|h| h.update(c:3) } elsif results.is_a?(hash) results.update(c:3) end
but looks ugly, messes code around (and i've got bug can't pin down)...
is there more elegant way this?
hopefully should work you.
# api simulator def call_api # lets return randomly - 1 of 3 results [ [{a: 1, b: 2}, {a:2, b:3}], {a: 1, b:2}, nil ].sample end 5.times r = [] r << call_api p r.flatten.compact.map { |h| h.update(c:3) } end
above code can written below:
5.times p [call_api].flatten.compact.map { |h| h.update(c:3)} end
the output array always, may empty or if contains hashes, have { :c => 3 }
in each of hashes. 1 of sample run produces below output:
[] [{:a=>1, :b=>2, :c=>3}] [] [{:a=>1, :b=>2, :c=>3}, {:a=>2, :b=>3, :c=>3}] [{:a=>1, :b=>2, :c=>3}]
Comments
Post a Comment