如何将一个方法的值从同一个类中的另一个方法中获取,以便我可以使用它?
示例:
def initialize var1
@var1 = var1
end
def method_a var2
#Here how can I use var1 to add it to var1 to make a var2
var2 = var1 + var1?
end
def method_b
#display
"#{@var1}, "#{var2}"
end
所以我要在method_a
中制作一个未初始化的第二个变量,然后将其显示在method_b
中。
答案 0 :(得分:2)
def method_a
@var2 = @var1 + @var1 # or: @var2 = @var1*2
end
def method_b
puts "#{@var1}, #{@var2}"
end
或者喜欢它的人:
class Foo
def initialize var1
@var1 = var1
@var2 = method_a #or change this string to call method_a, so just: method_a and this return @var2 = @var1*2
end
def method_a
@var1*2 #and there you should use variable @var2 = @var1 + @var1 (or @var1*2)
end
def method_b
p "#{@var1}, #{@var2}"
end
end
#=> boo = Foo.new(1)
#=> boo.method_b
#=> 1, 2