Take the 2-minute tour ×

I'm new to Ruby, how do I do something like this? in C#, I would have written


and it would work.

I'm imagining this function

def my_block
    yield 1
    yield 2
    yield 3

my_block.to_enum().map {|a| a}

This gives me this error:

test.rb:2:in `my_block': no block given (yield) (LocalJumpError)
    from test.rb:7:in `<main>'

What is the correct incantation for this behavior?

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

The correct syntax for your code is:

to_enum(:my_block).to_a # => [1,2,3]

Object#to_enum expects symbol with method name as its parameter:

to_enum(method = :each, *args)
enum_for(method = :each, *args)

Creates a new Enumerator which will enumerate by on calling method on obj.

Equivalent for C# ToList() is Enumerable#to_a

to_a → array
entries → array

Returns an array containing the items in enum.

share|improve this answer
Cool, I didn't know about that. –  David Grayson Jan 31 '12 at 16:50
add comment

You could change your function so it returns an Enumerable. Here is an example of how that would look:

def foo
  Enumerator.new do |y|
    y << 1
    y << 2
    y << 3

p foo        # => <Enumerator: #<Enumerator::Generator:0x1df7f00>:each>
p foo.to_a   # => [1, 2, 3]
p foo.map { |x| x + 1 }  # => [2, 3, 4]

Then you can use any of the methods in the Enumerable module on it:


A lot of ruby functions in the standard library will return an enumerable if they are NOT passed a block when they are called, but if they are passed a block they will yield values to the block. You could do that too.

share|improve this answer
Small correction, such functions in ruby 1.9 will return Enumerator, not Enumerable as you probably mistyped in the answer. Enumerator includes Enumerable module. –  Alex Kliuchnikau Jan 31 '12 at 17:02
Yeah. The object returned by the function is an Enumerator and it is also an Enumerable. foo.is_a?(Enumerable) returns true. With multiple inheritance I think it's OK to say an object is multiple things. I don't particularly care whether the function returns an Enumerator or not, I only care if it returns an Enumerable because that determines whether I can use all the useful methods on it like collect and select. –  David Grayson Jan 31 '12 at 17:12
Thanks David, I didn't know about this method. I could see it being helpful in building more well behaved libraries Alex's method is more concise for my needs, and doesn't require me to change the called function, just the caller. That said, your answer is still correct. But I guess I can only have one answer... –  Doug Jan 31 '12 at 17:48
add comment

Your Answer


