I only started looking into the Ruby language two days ago and have quickly learned that I am far too constrained into the mindset of C derived languages… I am trying to do the comparison on strings as such:
def menu_listen
action = gets
while !(action.eql?("up")) && !(action.eql?("down")) && !(action.eql?("close")) do
puts "'#{action}' is not a valid command at this time."
action = gets
end
return action
end
…which was earlier written as such:
def main_listen
action = gets
while action != "up" && action != "down" && action != "close" do
puts "'#{action}' is not a valid command at this time."
action = gets
end
return action
end
I read on this site that thisString.eql?(thatString) is the same as thisString == thatString, it would seem so because neither work. Any input I type into the command prompt does not get past the while loop and gives me this in response:
'down
' is not a valid command at this time.
So does this mean that the press of the enter key is also stored as a new line on the command prompt input? Can anyone tell me how to implement this so that the string comparison works properly?
getstakes in the eol character as well, so usegets.chompto only take in the actual string. Thechompmethod removes your carriage returns as well as your newlines.As far as the string comparison goes, it’s a little more ruby like to just compare whether or not your input exists in an array of predefined strings instead of chaining
&&andeql?, for example:This is cleaner than the chaining, and makes it easier to modify too.