简体   繁体   English

如何将键/值对添加到我的散列中?

[英]How do I add a key/value pair into my hash?

I am stuck in the below exercise.我被困在下面的练习中。

Instructions:指示:

Inside your when "add" block, remove the puts "Added."在你的 when “add” 块中,删除 puts “Added”。 statement.陈述。

In its place, prompt the user for a movie title.取而代之的是,提示用户输入电影名称。 Save the result in a new variable called title.将结果保存在名为 title 的新变量中。 (Your code already has an example of how to do this!) (您的代码已经有一个如何执行此操作的示例!)

Next, prompt the user for the rating of the movie.接下来,提示用户对电影的评级。 Save that in a new variable called rating.将其保存在一个名为 rating 的新变量中。

Add that movie/rating pair to the movies hash and puts a message indicating the pair was added.将该电影/评级对添加到电影散列中,并放置一条消息指示该对已添加。 (No need for to_sym or to_i just yet!) (暂时还不需要 to_sym 或 to_i!)

Code:代码:

movies = {"good fellas"=> "5"}
  puts "what's your favorite movie?"
  choice=gets.chomp
case choice
  when "add"
    puts "what's the movie you would like to add?"
    title=gets.chomp
    movies[title]
    puts"what's the rating for your selected movie?"
    rating=gets.chomp
    movies[title]=rating
  when "update"
    puts "Updated!"
  when "display"
    puts "Movies!"
  when "delete"
    puts "Deleted!"
else
    puts "Error!"
end

Adding a key/value pair to a hash can be done like this:可以像这样将键/值对添加到哈希中:

hash[key] = value

So in your case:所以在你的情况下:

when "add"
  puts "what's the movie you would like to add?"
  title=gets.chomp

  puts "what's the rating for your selected movie?"
  rating=gets.chomp

  movies[title] = rating
  puts "movie added"

Following should be your code以下应该是您的代码

movies = {"good fellas"=> "5"}
puts "what's your favorite movie?"
choice=gets.chomp
case choice
  when "add"
    puts "what's the movie you would like to add?"
    title=gets.chomp
    #movies[title]
    puts"what's the rating for your selected movie?"
    rating=gets.chomp
    movies[title]=rating
  when "update"
    puts "Updated!"
  when "display"
    puts "Movies!"
  when "delete"
    puts "Deleted!"
else
    puts "Error!"
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM