1

我目前的代码是这样的:

print "Feed me input."
def get_input
    input_value=gets.chomp
    if !input_value
      print "you didn't type anything"
    else
      input_value.downcase!
      if input_value.include? "s"
         input_value.gsub!(/s/,"th")
      else 
         print "You entered a string but it had no 's' letters."
      end
    end
   return input_value
end
get_input()
if !get_input
  get_input
  else 
    puts "#{get_input}"
end

我不确定为什么它不起作用。当我运行它时,我会提示输入,然后当我在输入 none 后按 enter 时,我得到“你输入了一个字符串,但它没有's'字母”,而不是我想要的“你没有输入任何东西”。

4

2 回答 2

3

false除了和之外的每个对象都nil被视为false用作谓词。即使是空字符串也被视为true

s = ""
puts true if s # => true

用于String#empty?检查是否为空字符串。

于 2013-10-05T06:11:32.357 回答
2

正如你所说,当我运行它时,我会提示输入,然后当我在输入 none 后按 enter 时- 这意味着实际发生的事情是

 input_value="\n".chomp #( you gets methods take only `\n` as input)
 "\n".chomp # => ""

所以你的input_value变量持有和空字符串对象。现在在 Ruby 中,每个对象都有true价值,除了niland false说这""也是真的,但你做到了!input_value,这意味着你正在false明确地做到这一点。这就是下面if-else块中的原因,else部分已执行并且您没有看到预期的输出"you didn't type anything"

if !input_value
      print "you didn't type anything"
    else
      input_value.downcase!
      if input_value.include? "s"
      #.. rest code.

因此,我建议您在这种情况下将行替换if !input_valueif input_value.empty?,这将使您的代码按预期运行。我没有把你的逻辑作为一个整体,而是试图向你展示如何编写代码来满足你的需求:

print "Feed me input."
def get_input
    input_value=gets.chomp
    if input_value.empty?
      puts "you didn't type anything"
      false
    else
      puts "found value" 
      input_value.downcase!
    end
end

until input = get_input
   # code
end
puts input

输出

kirti@kirti-Aspire-5733Z:~/Ruby$ ruby test.rb
Feed me input.
you didn't type anything

you didn't type anything

you didn't type anything
HH
found value
hh
kirti@kirti-Aspire-5733Z:~/Ruby$ 
于 2013-10-05T06:09:52.533 回答