gpt4 book ai didi

ruby - 使用 Ruby 的用户输入哈希

转载 作者:太空宇宙 更新时间:2023-11-03 17:51:31 27 4
gpt4 key购买 nike

我想问一个人,他们对他们的 friend 了解多少,他们最喜欢的游戏是什么。我想在我的循环迭代收集数据后打印它。这就是我尝试过的。我希望用户输入他们 friend 的名字和他们 friend 最喜欢的游戏,然后打印出来,但我想我是用 friend 和游戏的两个 gets.chomp 做的:

friendgame_hash = {} #this is where the hash starts I believe
input = "" #set input initially to nil
friend = "" #set friend to nil
game = "" #set game to nil
# starts the input from the user to get the name of their friend and favorite game
puts "Enter name of friend, then their favorite game: or Press Enter to quit " #
input = gets.chomp
while input != "" do #continue getting name of friend and their favorite game
(puts "Enter name of friend: ")
friend = gets.chomp
puts "Enter friends favorite game: "
game = gets.chomp

friendgame_hash[friend] = game #if understanding correctly hash key=friend value=game
input = gets.chomp #if user just presses enter they get out of while loop

end
puts "Here is the content that was in the hash: "
friendgame_hash.each do |key, value|
puts "#{key} => #{value}"
end

但是我得到以下错误:

(eval):20: (eval):20: compile error (SyntaxError)
(eval):8: odd number list for Hash
(eval):9: syntax error, unexpected tIDENTIFIER, expecting '}'
friend = gets.chomp
^
(eval):15: syntax error, unexpected '}', expecting kEND
(eval):18: syntax error, unexpected kDO_COND, expecting kEND
friendgame_hash.each do |key, value|
^
(eval):18: syntax error, unexpected '|', expecting '='

我不知道我哪里错了。任何帮助都会非常出色。我很好奇我是在正确的道路上还是在错误地解决问题。如有任何帮助,我们将不胜感激。

最佳答案

您有一个看起来像打字错误的变量名称,而且您没有像在 C 中那样将 {} 用于 while 循环。这是一个更正后的版本。

friendgame_hash = {}
input = ""
friend = ""
game = ""

puts "Enter name of friend, then their favorite game: or Press Enter to quit "
input = gets.chomp

# Curly braces after do were incorrect.
while input != "" do
puts "Enter name of friend: "
friend = gets.chomp
puts "Enter friends favorite game: "
game = gets.chomp

# There was a typo here
friendgame_hash[friend] = game
input = gets.chomp
end

puts "Here is the content that was in the hash: "
friendgame_hash.each do |key, value|
puts "#{key} => #{value}"
end

对于旧版本的 Ruby(1.8.7 和更早版本),将最后三行替换为下面的大括号语法。

friendgame_hash.each { |key, value|
puts "#{key} => #{value}"
}

关于ruby - 使用 Ruby 的用户输入哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23795378/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com