ruby - Ruby // 获取跨类通信的变量 // 为什么是 nil?
问题描述
为简单起见,我制作了以下两个类。我想把第一堂课中给出的信息用在整个课程的其他课程中。但是,我似乎无法让变量保留用户给出的值。
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
我已经尝试了上述类的一些变体,一些具有继承性,一些没有,初始化或没有,等等。它们似乎都输出'nil'。请指教。感谢您的时间。
解决方案
当 change 方法Changer
运行时,@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
推荐阅读
- python - 试图在数据集中找到最优价格点
- c# - Wpf.PropertyGrid ComboBox 来自自定义属性中的字符串数组
- reactjs - 如何向使用 create-react-app 制作的默认反应应用程序添加另一条路线?
- javascript - 使用 Sanctuary.js 合并多个对象
- avr - 为什么#define F_CPU 对AVR 代码_delay_ms_() 函数没有影响?
- angular - 带有 json-server 的 Angular 7 - 如何检索在发布响应中返回的 id?
- c++ - 具有 SPI_SETDESKWALLPAPER 函数的程序仅在尝试使用 C++ 将其更改为图像时将桌面背景更改为黑色
- dart - Flutter:AnimatedContainer - 子小部件的属性没有动画
- python - 如何将不同子目录中的多个 csv 文件中的值提取到新的 csv 文件中?
- json - ConverFrom-JSON:无效的 JSON 原语 DOT