2

I have a method which I want to act differently depending on the scenario, so I want to be able to pass a block to the method, and execute if the block is given.

However, I am confused by the scope of the variable in the block I am passing in.

For example:

def original_method (a, b, opt = {id: nil, id_map: {}})
  element_id = (opt[:id_map])

  yield if block_given?

end

And the new method which passes the block:

def new_method(a, b, opt)
 original_method (a, b, opt) do
  if(element_id.include? "some text")
    puts "it has some text"
  end
 end
end

But I get the error:

undefined local variable or method `element_id' 

at the yield line.

Can this be done?

1
  • you are missing a closing parenthesis after (opt[:id_map] Commented Nov 2, 2015 at 14:31

2 Answers 2

5

You need to pass the local variable element_id, as yield s argument.

def original_method (a, b, opt = {id: nil, id_map: {}})
  element_id = opt[:id_map]
  yield(element_id) if block_given? # pass it as argument
end

Then accept it like :

def new_method(a, b, opt)
 original_method (a, b, opt) do | element_id | # receive as block pramater
  if(element_id.include? "some text")
    puts "it has some text"
  end
 end
end

element_id local variable has been created inside the method original_method, that is why it is accessible inside this method only.

Inside the method new_method, when you are calling the method original_method with a block attached to it, due to closure capability it has access to all variables inside the method new_method from begining to the point where the block is created.

Sign up to request clarification or add additional context in comments.

Comments

1

Answer to your indirect question:

Blocks are scoped lexically, meaning that they have access to variables from the scope they're defined in (as opposed to "used in").

Comments

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.