Hash Flashcards
What is the use of flatten method in Hash?
Returns a new array that is a one-dimensional flattening of self hash
What is the difference between delete and delete_if methods?
Delete will delete a single entry
delete_if will delete the entries which block conditions evaluates to true.
Which method rebuilds the hash based on the current hash values for each key. If values of key objects have changed since they were inserted?
rehash method will reindex hash. a = [ "a", "b" ] c = [ "c", "d" ] h = { a => 100, c => 300 } h[a] #=> 100 a[0] = "z" h[a] #=> nil h.rehash #=> {["z", "b"]=>100, ["c", "d"]=>300} h[a] #=> 100
What would be output of the following code?
a = {1=> “one”, 2 => “two”, 3 => “three”, “ii” => “two”}
a.rassoc(“two”)
a = {1=> “one”, 2 => “two”, 3 => “three”, “ii” => “two”}
a.rassoc(“two”) #=> [2, “two”]
How will you make a duplicate copy of a hash?
h.clone
What are the ways to represent Ruby hash keys?
using symbol h = {:yahoo=>”xxxx”}
using string h ={“yahoo”=>”yyyy”}
What is the difference between length and size methods in hash?
No difference .they are all alias methods!!
to_h,to_a,to_s Please explain these methods?
They are used to convert one datatype into another.
Type casting
each method is imprtant in hash. What are the other possbile methods with each keyword?
each_key
each_value
each_pair
How to get a new hash from current hash values as keys, and the keys as values.?
invert method
In what order are the values of a hash iterated?
The order in which they were inserted.
Why can you safely use a string as a hash key, even though a string is mutable?
Because the interpreter makes a private copy of a string used as a hash key.
Does Hash use #== or #eql? to compare hash keys?
eql?
Write a function that sorts the keys in a hash by the length of the key as a string.
{ abc: ‘hello’, ‘another_key’ => 123, 4567 => ‘third’ } to
[“abc”, “4567”, “another_key”]
hsh.keys.collect(&:to_s).sort_by { |key| key.length }
What are the mehods to check hash keys?
Hash#has_key?, Hash#include?, Hash#member?