puts语句在两行打印

时间:2015-10-18 17:18:04

标签: ruby class puts

我有一个名为PolynomialElements的类,在该类中我有一个名为printElement的方法,它有一个put语句,可以打印两个变量。 puts语句在不同的行上打印变量。如何让puts在一行上打印两个变量。我的代码在下面,它是第5行,其中puts语句是。

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

1 个答案:

答案 0 :(得分:1)

while循环更改:

value = gets

为:

value = gets.chomp

然后你会得到:

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