Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby print hash key and value [closed]

Tags:

I'm trying to print key : value Currently I keep getting errors when I try to run my codes.

The code:

output.each do |key, value|     puts key + ' : ' + value end 

I can not figure out a way to do this on the same line. I've tried various implementations, like using the << symbol. I've also played around with print, using multiple puts statements, and appending both values into a string and printing that.

like image 768
thisisnotabus Avatar asked Sep 24 '13 19:09

thisisnotabus


People also ask

How do I print a hash key in Ruby?

A couple of other ways to get your hash key: Given the hash definition: myhash = Hash. new myhash["a"] = "Hello, " myhash["b"] = "World!"

How do I get the hash value in Ruby?

In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.

How do I iterate a hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.

How do you check if a hash has a key Ruby?

Overview. 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.


1 Answers

Depending on the contents of your Hash, you might need to convert the key to a string since it might be a symbol.

puts key.to_s + ' : ' + value 

Or, what I would suggest doing, use string interpolation:

puts "#{key}:#{value}" 

The reason you are getting an error, if key is indeed not a string, is because it is trying to call the method + on whatever key is. If it does not have a + method, you will get an error.

like image 113
Charles Caldwell Avatar answered Nov 03 '22 21:11

Charles Caldwell