简体   繁体   English

调用具有多个参数和一个块的方法的红宝石语法是什么?

[英]Whats the ruby syntax for calling a method with multiple parameters and a block?

Ruby doesn't like this: Ruby不喜欢这样:

item (:name, :text) {
  label('Name')
}

And I don't know why. 而且我不知道为什么。 I'm attempting to create a DSL. 我正在尝试创建DSL。 The 'item' method looks like this: “ item”方法如下所示:

def item(name, type, &block) 
  i = QbeItemBuilder.new(@ds, name, QbeType.gettype(type))
  i.instance_exec &block
end

Take a name for the item, a type for the item, and a block. 为项目取一个名称,为该项目取一个类型,以及一个块。 Construct an item builder, and execute the block in its context. 构造一个项目生成器,并在其上下文中执行该块。

Regardless of whether or not I need to use instance_exec (I'm thinking that I don't - it can be stuffed in the initialiser), I get this: 无论我是否需要使用instance_exec(我认为我不需要-它都可以填充在初始化程序中),我得到以下信息:

SyntaxError (ds_name.ds:5: syntax error, unexpected ',', expecting ')'
  item (:name, :text) {
              ^

How do I invoke method with multiple arguments and a block? 如何调用带有多个参数和一个块的方法? What does ruby think I'm trying to do? 红宝石认为我要做什么?

The space before parentheses is causing ruby to evaluate (:name, :text) as single argument before calling the method which results in a syntax error. 括号前的空格导致ruby在调用方法之前将(:name, :text)作为单个参数求值(:name, :text)这会导致语法错误。 Look at these examples for illustration: 请看以下示例进行说明:

puts 1      # equivalent to puts(1)       - valid
puts (1)    # equivalent to puts((1))     - valid
puts (1..2) # equivalent to puts((1..2))  - valid
puts (1, 2) # equivalent to puts((1, 2))  - syntax error
puts(1, 2)  # valid

Your way of providing the block is syntactically valid, however when the block is not in the same line as the method call it is usually better to use do ... end syntax. 您提供该块的方式在语法上是有效的,但是,如果该块与方法调用不在同一行,则通常最好使用do ... end语法。

So to answer your question you can use: 因此,要回答您的问题,您可以使用:

item(:name, :text) { label('Name') }

or: 要么:

item(:name, :text) do
  label('Name')
end

删除( item (:name, :text) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM