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.
A couple of other ways to get your hash key: Given the hash definition: myhash = Hash. new myhash["a"] = "Hello, " myhash["b"] = "World!"
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With