Ruby 打印哈希键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18990669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:11:48  来源:igfitidea点击:

Ruby print hash key and value

rubyhasheach

提问by thisisnotabus

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

我正在尝试打印 key : value 目前,当我尝试运行我的代码时,我不断收到错误消息。

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.

我想不出在同一条线上做到这一点的方法。我尝试了各种实现,比如使用 << 符号。我还玩过打印,使用多个 puts 语句,并将两个值附加到一个字符串中并打印出来。

回答by Charles Caldwell

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

根据 的内容Hash,您可能需要将 转换key为字符串,因为它可能是一个符号。

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 keyis indeed not a string, is because it is trying to call the method +on whatever keyis. If it does not have a +method, you will get an error.

如果key确实不是字符串,则出现错误的原因是它试图+在任何key情况下调用该方法。如果它没有+方法,你会得到一个错误。