[英]Syntax for putting a block on a single line
So I've got a Ruby method like this: 所以我有一个像这样的Ruby方法:
def something(variable, &block)
....
end
And I want to call it like this: 我想这样称呼它:
something 'hello' { do_it }
Except that isn't working for me, I'm getting a syntax error. 除非这对我不起作用,否则我会收到语法错误。 If I do this instead, it works: 如果我这样做,它的工作原理:
something 'hello' do
do_it
end
Except there I'm kind of missing the nice look of it being on one line. 除了那里,我有点想念它在一条线上的漂亮外观。
I can see why this is happening, as it could look like it's a hash being passed as a second variable, but without a comma in between the variables...but I assume that there must be a way to deal with this that I'm missing. 我可以看到为什么会发生这种情况,因为它看起来像是一个哈希作为第二个变量传递,但变量之间没有逗号...但我认为必须有一种方法来处理这个我'我失踪了。 Is there? 在那儿?
You need to parenthesize your argument: 你需要用括号括起你的论点:
something('hello') { do_it }
That should work. 这应该工作。
If you want "def something" to to accept a block, you need to yield data to that block. 如果你想要“def something”来接受一个块,你需要向该块产生数据。 For example: 例如:
#to uppercase string
def something(my_input)
yield my_input.upcase
end
# => "HELLO WORLD"
something("hello world") { |i| puts i}
Uh, what about: 呃,怎么样:
>> def something(arg1 , &block)
>> yield block
>> end
=> nil
>> def do_it
>> puts "Doing it!"
>> end
=> nil
>> something('hello') { do_it }
"Doing it!"
=> nil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.