【问题标题】:Error while defining custom array/hash method定义自定义数组/哈希方法时出错
【发布时间】:2012-05-12 05:35:37
【问题描述】:
def [](index)
  case index
  when 0, -2: @x
  when 1, -1: @y
  when :x, "x": @x
  when :y, "y": @y
  else nil
  end
end


array.rb:3: syntax error, unexpected ':', expecting keyword_then or ',' or ';' or '\n'
  when 0, -2: @x
             ^
array.rb:5: syntax error, unexpected ':', expecting keyword_end
  when :x, "x": @x
               ^
array.rb:6: syntax error, unexpected ':', expecting keyword_end
  when :y, "y": @y
               ^
array.rb:8: warning: else without rescue is useless
array.rb:9: syntax error, unexpected keyword_end, expecting $end

我是按照《Ruby 编程语言》一书的原样写的。

我的 ruby​​ 版本是 ruby​​ 1.9.3p0

有人见过吗?

【问题讨论】:

  • case/when 语句的语法从 ruby​​ 1.8 更改为 ruby​​ 1.9。这就是原因。
  • 不,不是。从未允许使用冒号语法,即使在 1.8 中也是如此。它只是意外地起作用了。

标签: ruby ruby-1.9


【解决方案1】:

我建议你使用常规的 case..when..then 形式

def [](index)   
  case index   
    when 0, -2 then @x   
    when 1, -1 then @y   
    when :x, "x" then @x   
    when :y, "y" then @y   
  end 
end 

【讨论】:

    【解决方案2】:

    试试“;”或换行符而不是“:”。

    case index
      when 0, -2; @x
    

    case index
      when 0, -2
        @x
    

    【讨论】:

    • 谢谢。您的解决方案也有效。我认为作者可能是想说; 而不是:
    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多