新手问题 一段 Ruby 代码报错

springwq · February 12, 2014 · Last by springwq replied at February 12, 2014 · 1954 hits

在看 Programming Ruby(ruby 2.0 版), 有下面一段代码,一直运行报错,提示enusre 关键字无法使用。不知道为什么会这样?

我的 ruby 版本是 2.1,切换到 2.0 同样是报错

  • 代码:
rate_mutex = Mutex.new
exchange_rates = ExchangeRates.new
exchange_rates.update_from_online_feed

Thread.new do
  rate_mutex.lock
  loop do
    rate_mutex.sleep 3600
    exchange_rates.update_from_online_feed
  end
end

loop do
  print "Enter currency code and amount: "
  line = gets
  if rate_mutex.try_lock
    puts(exchange_rates.convert(line)) ensure rate_mutex.unlock
  else
    puts "Sorry, rates being updated. Try again in a minute"
  end
end

  • 报错信息: ➜ prog_ruby ruby multiple_threads.rb multiple_threads.rb:17: syntax error, unexpected keyword_ensure, expecting keyword_end puts(exchange_rates.convert(line)) ensure rate_mutex.unlock ^
1 Floor has deleted

不是都说了语法错误吗?ensure 必须跟begin搭配使用吧。改成:

begin puts(exchange_rates.convert(line)) ensure rate_mutex.unlock end

试试?

You need to Sign in before reply, if you don't have an account, please Sign up first.