From: merch-redmine@... Date: 2019-02-19T15:15:48+00:00 Subject: [ruby-core:91594] [Ruby trunk Feature#15612] A construct to restrict the scope of local variables Issue #15612 has been updated by jeremyevans0 (Jeremy Evans). sawa (Tsuyoshi Sawada) wrote: > In order to improve readability of the code by explicitly indicating the scope of such local variables, and to avoid pollution by the variable, I propose to have some construct to restrict the scope of local variables. > > One possibility, without adding a new keyword to the current syntax, is to use the `begin`...`end` construct. The expected behavior would be: > > ```ruby > begin > foo = "foo" > foo # => "foo" > end > foo # => `nil`, or "Undefined local variable or method error" > ``` This would definitely break existing code. There is a lot of code that expects to be able to access local variables first assigned inside a begin/end block after the begin/end block. As blocks already do what you want, why not just: ```ruby tap do foo = "foo" foo # => "foo" end foo # => NameError ``` ```ruby foo = "bar" tap do foo = "foo" foo # => "foo" end foo # => "foo" ``` You can substitute another method that yields once for `tap` if you want. ---------------------------------------- Feature #15612: A construct to restrict the scope of local variables https://bugs.ruby-lang.org/issues/15612#change-76856 * Author: sawa (Tsuyoshi Sawada) * Status: Feedback * Priority: Normal * Assignee: * Target version: ---------------------------------------- We sometimes have local variables that are to be used only to keep track of some temporal states/values during a short routine: ```ruby ... foo = some_initial_value some_routine_that_uses_foo ... ``` Currently, the scope of local variables are either a proc, a block, `loop` body, a method definition, or a class/module definition, but such routines are sometimes just only a part of them. In order to improve readability of the code by explicitly indicating the scope of such local variables, and to avoid pollution by the variable, I propose to have some construct to restrict the scope of local variables. One possibility, without adding a new keyword to the current syntax, is to use the `begin`...`end` construct. The expected behavior would be: ```ruby begin foo = "foo" foo # => "foo" end foo # => `nil`, or "Undefined local variable or method error" ``` ```ruby foo = "bar" begin foo = "foo" foo # => "foo" end foo # => "bar" ``` Or, does this break the existing code too much? If so, can a new construct be added to the current syntax? -- https://bugs.ruby-lang.org/ Unsubscribe: