There are various types of variables and I didn't know how to use them properly, so I leave a note for myself.
local.rb
def local()
a = 3
end
p a
# =>Traceback (most recent call last):
local.rb:5:in `<main>': undefined local variable or method `a' for main:Object (NameError)
a defined by the local method cannot be called from outside the method.
instance.rb
class Instance
def set_val(val)
@val = val
end
def put_val
p @val
end
end
test1 = Instance.new
test1.set_val("aaa")
test1.put_val
test2 = Instance.new
test2.put_val
# =>
"aaa"
nil
Put "aaa" in @val of instance test1 using set_val method. After that, in instance test2, put_val is called, but nil is returned. From this, it can be seen that the value is held for each instance.
instance.rb
class Instance
def set_val(val)
@val = val
end
def put_val
p @val
end
end
test1 = Instance.new
test1.set_val("aaa")
test1.put_val
test2 = Instance.new
test2.set_val("bbb")
test2.put_val
# =>
"aaa"
"bbb"
It is necessary to use the set_val method for instance test2 as well.
class.rb
class Instance
def set_val(val)
@@val = val
end
def put_val
p @@val
end
end
test1 = Instance.new
test1.set_val("aaa")
test1.put_val
test2 = Instance.new
test2.put_val
# =>
"aaa"
"aaa"
Unlike the previous instance variable, the value is shared by all instances of the same class.
class.rb
class Instance
def set_val(val)
@@val = val
end
def put_val
p @@val
end
end
test1 = Instance.new
test1.set_val("aaa")
test1.put_val
test2 = Instance.new
test2.set_val("bbb")
test2.put_val
test1.put_val
# =>
"aaa"
"bbb"
"bbb"
global.rb
class Global
def set_val(val)
$val = val
end
end
test1 = Global.new
test1.set_val("aaa")
p $val
# =>
"aaa"
Recommended Posts