0

I trying to define a helper method that takes the Enumerable as arguments and should return processed values. Look at example of my problem.

>> def bar
>>   yield(->(x) { x.nil? })
>> end
>> bar { [nil, nil, 1].reject }
=> #<Enumerator: [nil, nil, 1]:reject>

I can't understand. An example below works as expected:

>> [nil, nil, 1].reject { |x| x.nil? }
=> [1]

What is missing here? Why i get a Enumerator instance instead of result?

1 Answer 1

2

The codeblock is not passed automagically to everything.

def bar 
   yield(->(x) { x.nil? })
end
bar do |p| 
  [nil, 1].reject &p
end

When you write

bar { ... }

you actually omit the yielded variable, exactly as in:

[1,nil].each { puts 'hey' }
Sign up to request clarification or add additional context in comments.

1 Comment

This is a very useful answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.