4

In C you can use statement blocks to isolate local variables from its parent scope.

int foo() {
    {
        int a;
    }
    // Here `a` is no longer in the scope.
}

But in Ruby the following fails to parse.

def foo
    do
        a = 1
    end
    puts a
end

Is there a trick to isolate variables into a scope in Ruby?

4
  • The notation for declaring an inline block is begin ... end, not do ... end. Commented Oct 8, 2014 at 20:28
  • 3
    In Ruby scope gates are created by 3 keywords.. def, class and module. Commented Oct 8, 2014 at 20:31
  • cs.auckland.ac.nz/references/ruby/doc_bundle/Newcomers/… Commented Oct 8, 2014 at 20:34
  • 1
    @tadman begin; a = 1; end; puts a prints 1, so a is not confined to the scope of the begin block. Commented Oct 9, 2014 at 0:07

2 Answers 2

3

The most appropriate "inner scope" in most cases is a separate method. Usually, if some of the data during a certain block of algorithm should not be visible outside, it's worth extracting this block into a separate method. And it could as well be, that this block could make a nice argument.

As the docs state, these are all the cases that have their own local variable scope:

  • proc{ ... } (and, consequently, blocks in method calls)
  • loop{ ... } (a method that accepts a block, same as above)
  • def ... end (a method implementation)
  • class ... end
  • module ... end
  • the entire program (this is of no use in scope of the question though)
Sign up to request clarification or add additional context in comments.

Comments

2

The following works, but I suspect there are other ways.

proc {
    a = 5
}.call

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.