Skip to content

Instantly share code, notes, and snippets.

@rozer007
Last active November 25, 2021 07:55
Show Gist options
  • Save rozer007/2489b69e4e08436fafa63d7908c08db4 to your computer and use it in GitHub Desktop.
Save rozer007/2489b69e4e08436fafa63d7908c08db4 to your computer and use it in GitHub Desktop.
Hashes in Ruby
Q1) Difference between update function and merge function ?
ans: Update combine 2 hashes in a destructive way with update or with no overwriting whereas merge function will just merge the two hash without overwritting
Q2) Can we convert hash from any array?
ans: No we can't ,for an array to convert to hash ,the number of elements in the array should be even.
Q3) How to access both key and value
ans: hash_name.each do|key,value|
end
Q4) How to set default value in hash while creating?
ans: We use Hash.new("default value")
Q1) What will be the output of this statement ?
hash=Hash.new("no such key")
hash["pep"]="coder"
puts hash["coder"]
a) pep
b) nil
c) no such key
d) none of the above
ans: c)no such key
Q2) What function is use to remove a key value pair in hash
a) hash.remove(key)
b) key.remove(hash)
c) hash.delete(key)
d) hash_name.delete(key)
ans: d) hash_name.delete(key)
Q3) What will be the output of this statement ?
h2=Hash["ko","po","lo","io"]
h3 = Hash["Lisa Morel", "Aquagirl", "Betty Kane", "Batgirl"]
h3.update(h2)
puts h3
a) {"ko","po","lo","io"}
b) {"Lisa Morel", "Aquagirl", "Betty Kane", "Batgirl"}
c) {"Lisa Morel"=>"Aquagirl", "Betty Kane"=>"Batgirl", "ko"=>"po", "lo"=>"io"}
d) none of the above
ans: d){"Lisa Morel"=>"Aquagirl", "Betty Kane"=>"Batgirl", "ko"=>"po", "lo"=>"io"}
Q4) What will this statement give :
h3 = Hash["A", "B", "C", "D","E"]
puts h3["A"]
a) "B"
b) "A"
c) error
d) nil
ans: c)error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment