Is there some reason for the whitespace not being allowed after yield keyword if the arguments I pass are in parentheses? This code will gather a mistake:

def who_says_what
yield ("rose","yay")
end
who_says_what {|flower,speech| puts "#{flower} says #{speech}"}

While this code can have as many whitespaces after yield as I'd like to:

def who_says_what
yield "rose","yay"
end
who_says_what {|flower,speech| puts "#{flower} says #{speech}"}
有帮助吗?

解决方案

The yield keyword is behaving no differently from the method invocation syntax. If you have a space between a method name and the parentheses containing the method's arguments, the interpreter parses the parentheses as passing a single argument that is the result of the expression inside of the parentheses.

Take this for example:

def foo
    yield('foo', 'bar')
end

foo {|x, y| print x, y }

The above outputs 'foobar' as expected.

def foo
    yield ('foo', 'bar')
end

foo {|x, y| print x, y }

Because parentheses for invoking a method are optional and are expected to immediately follow the name (or yield keyword in this case), here the block is being called with only one argument: the expression ('foo', 'bar').

However, a comma is unexpected in this expression and you get the SyntaxError exception. You can replicate the same error more simply by trying to evaluate the expression ('foo', 'bar') in irb.

This is legal:

def foo
    yield ('foobar')
end

foo {|x| puts x }

That correctly prints 'foobar' since the result of the expression ('foobar') is 'foobar', and that is the argument passed to the block.

Likewise, this prints 4 and 8 as one would expect:

def foo
    yield (2+2), (4+4)
end

foo {|x, y| puts x; puts y }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top