문제

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