Ruby // 获取变量以在 类 之间进行通信 // 为什么是 nil?
Ruby // Getting Variables to Communicate Across Classes // Why nil?
为了简单起见,我编造了以下两个 classes。我想获取第一个 class 中给出的信息,并在整个程序的其他 class 中使用它。但是,我似乎无法让变量保留用户给定的值。
class Input
attr_accessor :input
def initialize
@input = input
end
def call
get_input
# Changer.new.change(@input)
output
end
def get_input
puts "please write a number"
@input = gets.chomp.to_s
end
def output
p Changer.new.change(@input)
end
end
class Changer < Input
def change(input)
if @input == "one"
@input = "1"
elsif @input == "two"
@input = "2"
elsif @input == nil
"it's nil"
else
"something else"
end
end
end
Input.new.call
我已经尝试了上述class的一些变体,一些有继承,一些没有,初始化,或不等。它们似乎都输出'nil'。请指教。谢谢你的时间。
当Changer
中的change方法运行时,@input
是一个特定于那个Changer
实例的实例变量,它是nil。
您希望 change
方法处理提供给它的 input
参数,而不是 @input
。
def change(input)
if input == "one"
"1"
elsif input == "two"
"2"
elsif input == nil
"it's nil"
else
"something else"
end
end
或者更好:
def change(input)
case input
when "one"
"1"
when "two"
"2"
when nil
"it's nil"
else
"something else"
end
end
为了简单起见,我编造了以下两个 classes。我想获取第一个 class 中给出的信息,并在整个程序的其他 class 中使用它。但是,我似乎无法让变量保留用户给定的值。
class Input
attr_accessor :input
def initialize
@input = input
end
def call
get_input
# Changer.new.change(@input)
output
end
def get_input
puts "please write a number"
@input = gets.chomp.to_s
end
def output
p Changer.new.change(@input)
end
end
class Changer < Input
def change(input)
if @input == "one"
@input = "1"
elsif @input == "two"
@input = "2"
elsif @input == nil
"it's nil"
else
"something else"
end
end
end
Input.new.call
我已经尝试了上述class的一些变体,一些有继承,一些没有,初始化,或不等。它们似乎都输出'nil'。请指教。谢谢你的时间。
当Changer
中的change方法运行时,@input
是一个特定于那个Changer
实例的实例变量,它是nil。
您希望 change
方法处理提供给它的 input
参数,而不是 @input
。
def change(input)
if input == "one"
"1"
elsif input == "two"
"2"
elsif input == nil
"it's nil"
else
"something else"
end
end
或者更好:
def change(input)
case input
when "one"
"1"
when "two"
"2"
when nil
"it's nil"
else
"something else"
end
end