定义自定义数组/哈希方法时出错

时间:2012-05-12 05:35:38

标签: ruby ruby-1.9

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

有没有人见过这个?

2 个答案:

答案 0 :(得分:5)

我建议你使用常规案例......当时表格

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 

答案 1 :(得分:2)

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

case index
  when 0, -2; @x

case index
  when 0, -2
    @x