我正在尝试按值获取键,但想设置请求动态抛出字符串变量。
presidents = { 1 => "Washington", 2 => "Adams", 3 => "Jefferson" }
request1 = gets
request2 = "Adams"
puts presidents.rassoc(request1).first # doesn't work
puts presidents.rassoc(request2).first # work perfect
当我输入“Adams”并按 Enter 时,第二种方法会出错:
test.rb:6:in `<main>': undefined method `first' for nil:NilClass (NoMethodError)
我还检查了request1
课程request2
- 两者String
我阅读了rassoc的描述,但仍然不明白为什么第二个不起作用。