Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple printing key of a hash? [closed]

Tags:

ruby

hash

I want to print a key from a given hash key but I can't find a simple solution:

myhash = Hash.new
myhash["a"] = "bar"

# not working
myhash.fetch("a"){|k|  puts k } 

# working, but ugly
if myhash.has_key("a")?
    puts "a"
end

Is there any other way?

like image 395
mhd Avatar asked Aug 03 '10 04:08

mhd


People also ask

How do I print a hash key?

We can done this by using map function. map {print "$_\n"} keys %hash; map function process its statement for every keys in the hash.

How do you print hash values?

print "$ perl_print_hash_variable{'-hash_key2'} \n"; Description: The Perl print hash can used $ symbol for a single hash key and its value. The Perl print hash can use the % symbol for multiple hash keys and their values.

How can you tell if a key is present in a hash?

We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.

What is key in hash?

Answer: The hashing key is the raw data in which to be hashed. The hashing algorithm is the algorithm which performs a function to convert the hash key to the hash value. the hash value is what is produced as a result of the hash key being passed into the hashing algorithm.


1 Answers

To get all the keys from a hash use the keys method:

{ "1" => "foo", "2" => "bar" }.keys
=> ["1", "2"]
like image 139
Ryan Bigg Avatar answered Sep 22 '22 09:09

Ryan Bigg