使用Ruby的用户输入哈希

时间:2014-05-21 23:14:08

标签: ruby

我想问一个人他们对朋友的了解程度以及他们最喜欢的游戏是什么。我想在循环迭代收集数据后打印它。这是我试过的。我希望用户输入他们的朋友的名字和他们朋友最喜欢的游戏,然后打印出来,但我认为我用朋友和游戏的两个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 '='

我不知道我哪里错了。任何帮助都会很出色。我很好奇,如果我走在正确的道路上,或者我正在解决问题。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

您有一个看似拼写错误的变量名称,而且您不会像使用{}循环那样使用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}"
}