How do I access a hash value using a variable? Here's what I have that doesn't work:

DHASH = { 0 => -0.8,
          1 => -0.54,
          2 => -0.32,
          3 => -0.14,
          4 => 0,
          5 => 0.1 }

print "Enter number "
num = gets.chomp()
puts "Value: DHASH[#{num}]"

Output:

Enter number 2
Value: DHASH[2]

What I want:

Enter number 2
Value: -0.32
有帮助吗?

解决方案

Try this:

print "Enter number "
num = gets.chomp().to_i
puts "Value: #{DHASH[num]}"

Accessing hash values with a variable in Ruby is wonderfully easy! You just make sure the variable has the proper key, and then use the variable instead of the key. In your case, the number that you are getting will be a string, and you need it to be an integer, so you need to turn it into an integer. And you need to correct the string interpolation.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top