Search code examples
rubyclassputs

puts statement is printing on two lines


I have a class called PolynomialElements and inside that class I have a method called printElement that has a puts statement that print two variables. The puts statement is printing the variables on different lines. How do I get puts to print the two variables on one line. My code is below, it is line #5 where the puts statement is.

class PolynomialElements
  attr_accessor :element, :size

  def printElement
       puts "#{element}x^#{size}"
  end
end


askAgain = true
polyArray = Array.new

while askAgain
  puts "How many numbers do you want to enter? "
  numString = gets
  num = numString.to_i
  while num > 0
    puts "Enter a value for the Polynomial "
    value = gets
    polyArray.push(value)
    num -= 1
  end

  sizeOfArray = polyArray.length
  polyArray.each do |x|
    var = PolynomialElements.new
    var.element = x
    sizeOfArray -= 1
    var.size = sizeOfArray
    var.printElement
  end
  puts "Enter y to enter new number or anything else to quit"
  cont = gets
  if cont.chomp != "y"
    askAgain = false
  else
    polyArray.clear
  end
end

Solution

  • In the while loop change:

    value = gets
    

    to:

    value = gets.chomp
    

    You will then get:

    Enter a value for the Polynomial 
    3
    1x^2
    2x^1
    3x^0