LoginSignup
0
0

More than 1 year has passed since last update.

[py2rb] トップレベル変数

Last updated at Posted at 2022-01-04

はじめに

移植やってます。

トップレベル変数 (Python)

other.py
a = []

class A:
    def __init__(self, s=None) -> None:
        self.arr = list(s)

a.append([A('mon').arr, A('tue').arr])
main.py
import other

print(other.a)

# [[['m', 'o', 'n'], ['t', 'u', 'e']]]

トップレベルにあるローカル変数って凄いですね。
しかし、ファイル名+変数名なので、名前空間的には大丈夫そうではあります。

ローカル変数 (Ruby)

other.rb
a = []

class A
  attr_reader :arr
  def initialize(s=nil)
    @arr = s.split('')
  end
end

a << [A.new('mon').arr, A.new('tue').arr]
main.rb
require_relative 'other'

puts "#{a}"

# undefined local variable or method `a'

ぐぬぬ。

独習Ruby - P378

トップレベルで宣言されたローカル変数は、トップレベルだけで有効であり、(略)この点は、JavaScript、python など、ほかの言語に慣れていると、意外と混乱しやすい点でもあるので注意してください。

インスタンス変数 (Ruby)

other.rb
@a = []

class A
  attr_reader :arr
  def initialize(s=nil)
    @arr = s.split('')
  end
end

@a << [A.new('mon').arr, A.new('tue').arr]
main.rb
require_relative 'other'

puts "#{@a}"

# [[["m", "o", "n"], ["t", "u", "e"]]]

アクセスコントロールできるかどうか知らないGold持ち。

クラス変数 (Ruby)

other.rb
@@a = []

class A
  attr_reader :arr
  def initialize(s=nil)
    @arr = s.split('')
  end
end

@@a << [A.new('mon').arr, A.new('tue').arr]
main.rb
require_relative 'other'

puts "#{@@a}"

# warning: class variable access from toplevel
# [[["m", "o", "n"], ["t", "u", "e"]]]

warningを頂いてしまうし、Ruby3ではRuntimeErrorになるらしい。

グローバル変数 (Ruby)

other.rb
$a = []

class A
  attr_reader :arr
  def initialize(s=nil)
    @arr = s.split('')
  end
end

$a << [A.new('mon').arr, A.new('tue').arr]
main.rb
require_relative 'other'

puts "#{$a}"

# [[["m", "o", "n"], ["t", "u", "e"]]]

staticおじさんに近いが。

トップレベル定数 (Ruby)

other.rb
AA = []

class A
  attr_reader :arr
  def initialize(s=nil)
    @arr = s.split('')
  end
end

AA << [A.new('mon').arr, A.new('tue').arr]
main.rb
require_relative 'other'

puts "#{AA}"

# [[["m", "o", "n"], ["t", "u", "e"]]]

定数ですと、名前が被った時にアラートが出るので、ひとまずこれで行こう。

メモ

  • Python の トップレベル変数 を学習した
  • 道のりは遠そう
0
0
1

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
0
0