0

我正在尝试按值获取键,但想设置请求动态抛出字符串变量。

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的描述,但仍然不明白为什么第二个不起作用。

4

1 回答 1

1

你错过了gets

# If the user types 'Washington'
gets       #=> "Washington\n"
gets.chomp #=> "Washington"
于 2013-03-08T19:10:46.560 回答