0

所以我在下面有一个例子:

movies = {
  dobby: "dobster is a lad",
  pirates_of_the_carribean: "Its all about jack sparrow kicking ass!"
  }
puts "what do you want to know about?\n
#{movies[:dobby]}. = 1\n
or...\n
#{movies[:pirates_of_the_carribean]}. = 2\n
Pick a number :"

现在我得到的是valuekey 的,但我希望得到的Key只是puts输出key而不是value.

我知道该解决方案可能会输出密钥,:key而不是key这样 id 还想知道如何在没有“:”的情况下返回密钥以用于显示目的。

注意:我已经使用谷歌进行了彻底的搜索,还没有找到解决这个问题的方法。

4

2 回答 2

1

所以我在一个问类似问题的问题中找到了答案。为了找到我使用的.keys[]方法的关键,我的结果代码是这样的:

movies = {
  dobby: "dobster is a lad",
  pirates_of_the_carribean: "Its all about jack sparrow kicking ass!"
  }
puts "what do you want to know about?\n
#{movies.keys[0]}. = 1\n
or...\n
#{movies.keys[1]}. = 2\n
Pick a number :"

此代码打印出没有 的键:,因此#{movies.keys[1]}打印出pirates_of_the_carribean.

于 2017-10-21T04:47:48.640 回答
0

您可以在哈希中使用该keys方法:movies

movies = {
  dobby: "dobster is a lad",
  pirates_of_the_carribean: "Its all about jack sparrow kicking ass!"
}

puts "What do you want to know about?" 
counter=0
movies.keys.each do |k|
   counter += 1
   puts "#{k}. = #{counter} "
end 
puts "Pick a number:"
于 2017-10-21T10:05:07.367 回答