本文介绍了案例陈述未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为 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)
我总是得到 你给了 MYCHOSENOPTION -- 我不知道该怎么做.
,无论我选择什么选项.如果我在比较 1 的 case
之前放置一个 if
,它似乎与我的字符串不匹配.
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,我将如何编写这个程序:
FWIW, here is how I would write this program:
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)
注意事项:
- 方法中的最后一个表达式是返回值;在 Ruby 中几乎不需要或不需要使用
return
. - 存在用于反转字符串和数组的内置方法.(我理解你这样做是为了练习.)
在 Ruby 中使用
for
迭代数组或字符串很麻烦.相反,您应该使用
- The last expression in a method is the return value; using
return
is almost never needed or desirable in Ruby. - There exist built-in methods for reversing strings and arrays. (I understand if you are doing this for an exercise.)
It is cumbersome to iterate arrays or strings in Ruby using
for
. Instead, you should use
my_str.each_char do |char|
# use the single-character string `char` here
end
my_array.each do |item|
# use the item here
end
您可以使用 $stdout.sync
强制输出总是被刷新.
You can use $stdout.sync
to force output to always be flushed.
这篇关于案例陈述未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!