The code below works as I want, switching a light on or off with each keypress of l. However, when I try to add other things I want done with the switching, I can’t.
look = 0
lighton = 0
while look < 10
system 'stty cbreak'
q = $stdin.sysread 1
case q ### #{q}
when "l" then if lighton==1 then lighton=0 and puts "ight off"
else lighton=1 and puts "ight on" end
end
system 'stty cooked'
look += 1
end #while
If I add another and it isn’t seen but I get no error:
look = 0
lighton = 0
while look <10
system 'stty cbreak'
q = $stdin.sysread 1
case q ### #{q}
when "l" then if lighton==1 then lighton=0 and puts "ight off" and puts "light still off"
else lighton=1 and puts "ight on" end
end
system 'stty cooked'
look += 1
end #while
I’d like to add several more statements to both the if and else portions but can’t.
There’s no limit, you’re just misusing the
andoperator. It’s not meant to do “this and that”, it does “do this and, if it is truthy, do this too”. Here’s a quick example:Since
putsreturnsnil, which is falsy,puts 'hello' and puts 'world'will only print “hello”.So, don’t use
andto create a one-liner. You could use;instead, but that doesn’t help readability. Instead just use multiple lines! It’s much clearer what’s going on:You may wish to read more about
and/orin Ruby and how they differ from&&/||.