ruby - comparing keys in one array with another -
ruby newbie here. have been banging head against wall better part of 2 hours due assignment have. create method has 2 arguments - hash , array of keys derived hash's keys. method should return true if array has of keys in hash, , false if not. have make sure every key in hash argument contained in array_of_keys argument. method should return true if of elements in array_of_keys array within set of keys in hash argument, without regard specific order. writers of assignment suggested using .sort method this.
this have far, having issue figuring out how sort both arrays in order compare.
def do_i_have?(hash, array_of_keys) array_of_keys = [] hash.each |key, value| array_of_keys << key end hash.keys == array_of_keys end
i have tried, no luck.
def do_i_have?(hash, array_of_keys) array_of_keys = [] hash.each |key, value| array_of_keys << key end hash.keys.sort == array_of_keys.sort end
what correct syntax in order sort , compare these 2 arrays?
thanks guys!
when use second method, rspec tells me:
do_i_have? returns true if keys in hash do_i_have? returns true if keys in hash, regardless of order
but,
do_i_have? not return false if doesn't have of keys do_i_have? not return false if 1 or more of keys isn't in hash do_i_have? not return false if hash has different number of keys array
rspec:
describe "do_i_have?" "returns false if doesn't have of keys" h = { name: "computer", cost: "$1,000" } keys = [:age, :bio] expect( do_i_have?(h, keys) ).to eq(false) end "returns false if 1 or more of keys isn't in hash" h = { name: "computer", cost: "$1,000" } keys = [:name, :bio, :cost] expect( do_i_have?(h, keys) ).to eq(false) end "returns false if hash has different number of keys array" h = { name: "computer", cost: "$1,000" } keys = [:name] expect( do_i_have?(h, keys) ).to eq(false) end "returns true if keys in hash" h = { name: "computer", cost: "$1,000", uuid: "1234" } keys = [:name, :cost, :uuid] expect( do_i_have?(h, keys) ).to eq(true) end "returns true if keys in hash, regardless of order" h = { name: "computer", cost: "$1,000", uuid: "1234" } keys = [:name, :uuid, :cost] expect( do_i_have?(h, keys) ).to eq(true) end end
this feels cheating, why not...
$ cat foo.rb def do_i_have?(hash, array_of_keys) hash.size == (hash.keys & array_of_keys).size end hash = {a: 1, b: 2, c: 3} puts do_i_have?(hash, [:a, :b, :c]) puts do_i_have?(hash, [:c, :a, :b]) puts do_i_have?(hash, [:a, :b])
and when run:
$ ruby foo.rb true true false
no need sort them... hash.keys & array_of_keys
contain fields common both arrays (excluding duplicates). if same size keys in hash, have same set, right?
Comments
Post a Comment