LoginSignup
18
17

More than 5 years have passed since last update.

Rubyでの変数スコープ(クラス、メソッド、制御構文、ブロック)について

Last updated at Posted at 2015-07-16

Rubyでの変数スコープ(クラス、メソッド、制御構文、ブロック)について

Rubyでの変数のスコープのメモ。
インスタンス変数やクラス変数ではなく、ローカル変数を対象としています。

class Scope
  _top = "top level"

  p _top # => "top level"

  def scope_method
    _method = "method level"

    p _method # => "method level"
    # p top => 外のスコープは見えないためエラー発生

    # 制御構文
    ## if
    if true
      _if = "if level"
      p _method # => "method level"
    end
    p _if # => "if level"

    ## for
    for _var in 1..5
      _for = "for level"
    end
    p _for # => "for level"
    p _var # => 5

    ## while
    num = 0
    while num <= 0
      _while = "while level"
      num += 1
    end
    p _while

    ## case
    case
      when num == 1
        _case = "case level"
    end
    p _case
    ## begin
    begin
      _begin = "begin level"
      raise
    rescue
      p _begin # => "begin level"
    ensure
      p _begin # => "begin level"
    end

    ## ブロック
    ary = (1..10).to_a
    ary.each do |block_num|
      p block_num # => 1~10
    end
    # p block_num # => エラー発生。ブロック内のスコープに閉じられている。
  end

  # p _method # => エラー発生

  # インナークラス
  class InScope
    _inner = "inner"
    # p _top # => エラー発生
  end
  # p _inner # => エラー発生
end

obj = Scope.new
obj.scope_method

結論

  • class外では、class内やメソッド内のローカル変数を見れない。
  • class内では、トップレベルに宣言されたローカル変数しか見えない。
  • メソッド内では、変数のスコープはメソッド内に閉じ(メソッド外のローカル変数は見れない)、制御構文内のメソッドは見れる。
  • 制御構文(if,forなど)では、メソッド内のローカル変数を見れる。
    • 制御構造はスコープを作らない。
  • ブロック内では、メソッド内のローカル変数を見れる。
18
17
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
17