Ethan Turkeltaub
Ethan Turkeltaub

Reputation: 2961

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.

Upvotes: 1

Views: 343

Answers (3)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121020

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]

Upvotes: 0

DigitalRoss
DigitalRoss

Reputation: 146281

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]

Upvotes: 0

dirk
dirk

Reputation: 271

That syntax is not allowed in Ruby, so unfortunately that is impossible since the code won't even make it past the parser.

Upvotes: 3

Related Questions