【问题标题】:Ruby // Getting Variables to Communicate Across Classes // Why nil?Ruby // 获取跨类通信的变量 // 为什么是 nil?
【发布时间】:2021-11-10 02:26:23
【问题描述】:

为简单起见,我制作了以下两个类。我想把第一堂课中给出的信息用在整个课程的其他课程中。但是,我似乎无法让变量保留用户给出的值。

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'。请指教。感谢您的宝贵时间。

【问题讨论】:

  • Changer 中的change 方法运行时,@input 是特定于该Changer 实例的实例变量,它是 nil
  • 你应该删除继承:Changer 是它自己的一个类,而不是专门的Input

标签: ruby class inheritance


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2014-09-20
    • 2012-03-20
    • 1970-01-01
    • 2014-08-03
    • 2012-02-13
    • 1970-01-01
    相关资源
    最近更新 更多