Home > OS >  Ruby // Getting Variables to Communicate Across Classes // Why nil?
Ruby // Getting Variables to Communicate Across Classes // Why nil?

Time:11-10

I have the following two classes I fabricated for simplicity. I would like to take the information given in the first class, and use it in other classes throughout the program. However, I can not seem to get the variable to retain it's value given by the user.

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

I have tried a few variations on the above classes, some with inheritance, some without, initializing, or not, etc. They all seem to output 'nil'. Please advise. Thank you for your time.

CodePudding user response:

When the change method in Changer runs, @input is an instance variable specific to that Changer instance, and it is nil.

You want your change method to work on the input argument being provided to it, rather than @input.

  def change(input)
    if input == "one"
      "1"
    elsif input == "two"
      "2"
    elsif input == nil
      "it's nil"
    else
      "something else"
    end
  end

Or better yet:

  def change(input)
    case input
      when "one"
        "1"
      when "two"
        "2"
      when nil
        "it's nil"
      else
        "something else"
    end
  end
  • Related