首页 > 解决方案 > 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'。请指教。感谢您的时间。

标签: rubyclassinheritance

解决方案


当 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

推荐阅读