Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>FWIW, here is how I would write this program:</p> <pre><code>def ask(prompt) print "#{prompt} " gets.chomp end def myreverse(s) s.reverse end def mywordreverse(s) s.split(' ').reverse.join(' ') end def choose(s,option) case option when 1 then puts myreverse(s) when 2 then puts mywordreverse(s) when 3 then puts "hello" else puts "You gave me #{option}; I don't know what to do with that." end end $stdout.sync str = ask("Write a string to reverse: ") option = ask("Choose an option:\n1: Reverse string\n2: Reverse String words\n&gt;") choose(str,option.to_i) </code></pre> <p>Notes:</p> <ol> <li>The last expression in a method <em>is</em> the return value; using <code>return</code> is almost never needed or desirable in Ruby.</li> <li>There exist built-in methods for reversing strings and arrays. (I understand if you are doing this for an exercise.)</li> <li><p>It is cumbersome to iterate arrays or strings in Ruby using <code>for</code>. Instead, you should use</p> <pre class="lang-ruby prettyprint-override"><code>my_str.each_char do |char| # use the single-character string `char` here end my_array.each do |item| # use the item here end </code></pre></li> <li><p>You can use <code>$stdout.sync</code> to force output to always be flushed.</p></li> <li>You need to use <code>chomp</code> on your string to remove the trailing newline always included when the user presses Enter.</li> <li>As pointed out by @robbrit, the core of your problem is that the return value of <code>gets</code> is a String, and you are comparing it to a Fixnum. I've used <code>to_i</code> in my code above to convert the string to an integer for comparison.</li> <li>I've used <code>puts</code> instead of <code>print</code> for 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.</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload