简体   繁体   中英

Ruby Block to Array

I'm trying to take a block argument in a method, and turn the contents (array of Symbols) and make it into an array. For example:

def sequence(&block)
  # ?
end

sequence do
  :foo,
  :bar,
  :foobar
end # => [:foo, :bar, :foobar]

I know it would be easier to just have an array as an argument in the sequence method, but I'm trying to stay consistent with another method.

Ruby中不允许使用该语法,因此不幸的是,这是不可能的,因为代码甚至不会通过解析器。

Ok, not answering the exact question, and I imagine you and dirk know this, but...

In case someone wants an Array as a parameter and their search has led them here, Ruby does have a basic feature that does something similar for you:

def f *x
  x
end

p f :foo,
    :bar,
    :foobar 

# => [:foo, :bar, :foobar]

Though the syntax you suggested will not pass a parser, there are some tweaks:

def sequence(&block)
  yield
end

sequence do [
  :foo,
  :bar,
  :foobar
] end # => [:foo, :bar, :foobar]

sequence do _= 
  :foo,
  :bar,
  :foobar
end # => [:foo, :bar, :foobar]

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