我想使用gets
的输入来访问哈希值。
此代码不起作用:
puts "Which word?"
question = gets
question = question.to_s
puts dic_hash["#{question}"]
也不是这样:
puts "Which word?"
question = gets
question = question.to_s
puts dic_hash[question]
但这有效:
puts "Which word?"
puts dic_hash["zwembad"]
如何从用户那里获取gets
输入以访问哈希值?
答案 0 :(得分:3)
您可能没有意识到这一点,但gets
结果包含您输入的返回字符以提交值。
result = gets
输入“hello”
p result
"hello\n"
将您的gets
更改为gets.chomp
以删除尾随的'\ n`
puts "Which word?"
question = gets.chomp
puts dic_hash[question]