I have one single file called Exercises.rb
def ask(prompt)
print prompt, ' '
$stdout.flush
s = gets
return s
end
def myreverse(s)
aux=""
for i in 0..s.length-1
aux=s[i] + aux
end
return aux
end
def mywordreverse(s)
aux=[]
s=s.split(" ")
for i in 0..s.length-1
aux.unshift(s[i])
end
return aux.join(" ")
end
def choose(s,option)
case option
when 1 then print myreverse(s)
when 2 then print mywordreverse(s)
when 3 then print "hello"
else print "You gave me #{option} -- I have no idea what to do with that."
end
end
s=ask("Write a string to reverse: ")
option=ask("Choose an option. 1 - Reverse string. 2 - Reverse String words : ")
choose(s,option)
I am always getting You gave MYCHOSENOPTION -- I have no idea what to do with that., no matter what option I choose. If I put an if just before the case comparing 1, it just doesn’t seem to be matching the option to my strings.
FWIW, here is how I would write this program:
Notes:
returnis almost never needed or desirable in Ruby.It is cumbersome to iterate arrays or strings in Ruby using
for. Instead, you should useYou can use
$stdout.syncto force output to always be flushed.chompon your string to remove the trailing newline always included when the user presses Enter.getsis a String, and you are comparing it to a Fixnum. I’ve usedto_iin my code above to convert the string to an integer for comparison.putsinstead ofprintfor the output so that I get a newline at the end and do not leave the user with their next command prompt on the same line as the output.