简体   繁体   中英

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

Ruby doesn't like this:

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

And I don't know why. I'm attempting to create a DSL. The 'item' method looks like this:

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:

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. 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.

So to answer your question you can use:

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

or:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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