1

と呼ばれる単一のファイルがあります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)

You gave MYCHOSENOPTION -- I have no idea what to do with that.どのオプションを選択しても、常に取得しています。if比較する 1 の直前にa を付けるとcase、オプションが文字列に一致していないように見えます。

4

2 に答える 2

2

これを試して:

 case option.to_i
    # rest of your code...

Ruby では1 == "1"(より具体的にはcaseステートメントの場合1 === "1") は常に に評価されfalseます。比較を行う前に、それらの 1 つを同じ型になるように変換する必要があります。渡す値optionはおそらく aStringであるため、整数との比較では失敗します。

于 2012-06-25T16:55:44.417 に答える
1

FWIW、これが私がこのプログラムを書く方法です:

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>")
choose(str,option.to_i)

ノート:

  1. メソッドの最後の式戻り値です。Ruby では、を使用returnする必要はなく、望ましいこともほとんどありません。
  2. 文字列と配列を逆にするための組み込みメソッドが存在します。(練習のためにこれを行っている場合は理解しています。)
  3. を使用して Ruby で配列や文字列を反復処理するのは面倒forです。代わりに、使用する必要があります

    my_str.each_char do |char|
      # use the single-character string `char` here
    end
    
    my_array.each do |item|
      # use the item here
    end
    
  4. $stdout.sync出力を常にフラッシュするように強制するために使用できます。

  5. chompユーザーがEnterを押したときに常に含まれる末尾の改行を削除するには、文字列で使用する必要があります。
  6. @robbritが指摘したように、問題の核心は戻り値がgets文字列であり、それをFixnumと比較していることです。to_i上記のコードで、比較のために文字列を整数に変換するために使用しました。
  7. 最後に改行を取得し、出力と同じ行に次のコマンドプロンプトが表示されないように、出力のputs代わりに使用しました。print
于 2012-06-25T17:12:11.083 に答える