【问题标题】:How do I add a key/value pair into my hash?如何将键/值对添加到我的哈希中?
【发布时间】:2019-12-13 17:55:29
【问题描述】:

我被困在下面的练习中。

说明:

在“添加”块中,删除“添加!”声明。

在其位置提示用户输入电影名称。将结果保存在名为 title 的新变量中。 (您的代码已经有一个如何做到这一点的示例!)

接下来,提示用户为电影评分。将其保存在名为 rating 的新变量中。

将该电影/评分对添加到电影哈希中,并放置一条消息,指示该对已添加。 (现在还不需要 to_sym 或 to_i!)

代码:

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

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    向散列添加键/值对可以这样完成:

    hash[key] = value

    所以在你的情况下:

    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"
    

    【讨论】:

      【解决方案2】:

      以下应该是您的代码

      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
      

      【讨论】:

        猜你喜欢
        • 2018-08-22
        • 2019-04-12
        • 2012-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-09
        • 1970-01-01
        相关资源
        最近更新 更多