新手问题 Ruby2.0 后 yield 只能接收一个参数了么?

Unknow user · September 07, 2013 · Last by Rei replied at September 08, 2013 · 3581 hits

我在调试《Ruby 元编程》第 87 页的代码时,遇到了上述的疑惑,求大神帮忙解惑; 87 页的具体代码如下:

def math (a, b) yield(a,b) end def teach_math (x, y,&operation) puts “let's do the math” puts math (x, y,&operation) end

teach_math(2,3) { | c, d | c*d } #==> Let's do the math 6

然后我在 irb 中得到的语法错误如下图

你的标点不是用的英文半角吧?

yield (a,b)

不要加空格 要么加了空格就不要用括号

Unknow user #3 September 07, 2013

#1 楼 @showlovel 是纯英文输入状态的,再说前面那个 math(a,b)也没有报错啊。就想知道是不是 ruby2.0 把 yield 改动了

Unknow user #4 September 07, 2013

#2 楼 @Ddl1st 谢了,去掉括号后那个程序还是没有调试成功。不过 yield 的问题解决了:

我测过这程序没有问题

Unknow user #6 September 07, 2013

#5 楼 @AlphaLiu 你测试时用的也是 win8 64bit +ruby2.0 的环境吗?我这边一直会报语法错误。

def math(a, b)
  yield(a, b)
end

def teach_math(x, y, &operation) 
  puts "let's do the math" 
  puts math(x, y, &operation) 
end

teach_math(2,3) { | c, d | c*d } 

你的代码里有全角的逗号,括号。试试上面的在你那能运行不

Unknow user #8 September 08, 2013

#7 楼 @reyesyang 谢谢,把你打代码复制过来,可以运行

楼主请把代码格式化好,是否对格式有着苛刻的自我要求跟你这次遇到的问题是有关的。

http://ruby-china.org/topics/8518

如果格式化好你自己就能看出问题

def math (ab)
      yieldab
end
def teach_mathxy&operation 
        puts let's do the  math” 
        puts math (x,y,&operation) 
end

teach_math(2,3)  {     |  c,d  |      c*d  }                      #==>  Let's  do the math
                                                                                               6
You need to Sign in before reply, if you don't have an account, please Sign up first.