Думаю, этот метод должен работать:
def reject(hash_var, ele)
# Find the index of the ele
# If it is found, just remove it and return hash_var
idx = hash_var.index(ele)
if idx
hash_var.delete_at(idx)
return hash_var
end
# Convert the hashes to arrays - 2D arrays
# { "b" => "2" } becomes [["b", "2"]]
(0...hash_var.length).each do |n|
if hash_var[n].class == Hash
hash_var[n] = hash_var[n].to_a
end
end
(0...hash_var.length).each_with_index do |n, i|
# Only operate if hash_var[n] is an array
# this means that this is 2D array i.e. hash
if hash_var[n].class == Array
# If this is just as element, delete the whole hash_key
# i.e. reject(hash_var, "a")
# here ele = "a", so since this is not hash
# we need to delete full element i.e. ["aa", "bb", "cc"]
if hash_var[n][0][0] == ele
hash_var.delete_at(i)
else
next if ele.class == String
ele_a = ele.to_a
if hash_var[n][0][0] == ele_a[0][0]
diff = hash_var[n][0][1] - ele_a[0][1]
hash_var[n][0][1] = diff
end
end
end
end
## Convert the 2D arrays back to hashes
(0...hash_var.length).each do |n|
if hash_var[n].class == Array
hash_var[n] = hash_var[n].to_h
end
end
# return final
return hash_var
end
Тесты:
hash_var = ["1", "2", {"a" => ["aa", "bb", "cc"]}]
p reject(hash_var, "1")
# => ["2", {"a"=>["aa", "bb", "cc"]}]
p reject(hash_var, "a")
# => ["1", "2"]
p reject(hash_var, {"a" => ["aa"]})
# => ["1", "2", {"a"=>["bb", "cc"]}]