Question on while loop to script

Hi guys,

I’m new to ruby and I’m writing simple programs to help my understanding
of ruby. I wrote the program below and I would like to know if you guys
could recommend a while loop to use before the if statement so the
program doesn’t end until a key is pressed? I want it to keep running
until the user quits. Also does anyone think I can make the program
better?class OhmsLaw
def initialize(voltage, current, resistance)
@voltage = voltage
@current = current
@resistance = resistance
end
def voltageNil
@current * resistance
end
def currentNil
@voltage / @resistance
end
def resistanceNil
@voltage / @current
end
def to_s
“String representation of OhmsLaw V: #{@voltage}, I: #{@current}, R:
#{@resistance}”
end

#This will make these variables accessoable from outside
#of the class

attr_accessor :voltage, :current, :resistance
#solve4Current can be used for :currentNil as an alias for it
alias :solve4Current :currentNil
end

#created a new object called solve that will take V,I,R as inputs
solve = OhmsLaw.new(9.0, nil, 2)
#attr_accessor allows us to change voltage of 9 to 16 volts from
#outside of the class
solve.voltage = 16

if solve.voltage == nil
puts solve.voltageNil
elsif solve.current == nil
puts solve.solve4Current
else
puts solve.resistanceNil
end

puts “#{solve}”

On Jul 22, 2013, at 6:50 PM, “Talal B.” [email protected] wrote:

@current = current
end
end
puts solve.solve4Current
else
puts solve.resistanceNil
end

puts “#{solve}”


Posted via http://www.ruby-forum.com/.

Welcome!

I’m of two minds here:

  1. writing a REPL (read-eval-print loop) is a worthy exercise in itself,
    so yes
  2. if you just want to work with your class, you can use irb as your
    REPL, so maybe not yet

You can make your code a bit shorter still.

puts “#{solve}”

No need to do that. Simply do:

puts solve

And also:

if solve.voltage == nil
puts solve.voltageNil
elsif solve.current == nil
puts solve.solve4Current
else
puts solve.resistanceNil
end

could become:

if solve.voltage.nil?
puts solve.voltageNil
elsif solve.current.nil?
puts solve.solve4Current
else
puts solve.resistanceNil
end

Thanks so much for your help but what I’m looking for is

while key.pressed =! q
if solve.voltage.nil?
puts solve.voltageNil
elsif solve.current.nil?
puts solve.solve4Current
else
puts solve.resistanceNil
end
end

Does anyone know how i may be able to accomplish this goal?

On Jul 23, 2013, at 3:55 PM, Talal B. [email protected] wrote:

Thanks so much for your help but what I’m looking for is

while key.pressed =! q

loop do
print "Type ‘q’ to quit: ’
break if gets[0] == ‘q’