有没有更好的方法不重复自己(红宝石)?

时间:2014-03-03 13:08:23

标签: ruby

有没有更好的方法来写这个?我不喜欢连续三次写“回应”这个词

puts 'Good Day! Would you like a practice program?'

choices = [1,2,3,4,5]

while true
  response = gets.chomp
  if  response == 'yes' || response =='YES' || response == 'Yes' 
    puts 'Here\'s your number.'
    puts choices.sample
    break
  else
    puts 'try again.'
  end 
end

5 个答案:

答案 0 :(得分:4)

尝试

  response = gets.chomp
  if  response.downcase == 'yes'
   # statements
  else
   # statements
  end

此处响应值'yes'可以是值的任意组合,如

  是的,是的,是的,是的,是的,是的,是的,等等。

答案 1 :(得分:4)

另一种方式,只是为了它:

['Yes', 'YES', 'yes'].include? response

答案 2 :(得分:2)

我会写如下:

puts 'Good Day! Would you like a practice program?'

choices = [1,2,3,4,5]
# Kernel#loop repeatedly executes the block, until you break it 
loop do
  response = gets.chomp
  # Regexp#=== will be the good choice here to do the matching
  if  /^(yes|YES|Yes)$/ === response 
  # For any combination of yes values /^yes$/i === response
    puts %{Here's your number: #{choices.sample}}
    break
  else
    puts 'try again.'
  end 
end

让我们运行代码:

C:\ruby>ruby so.rb
Good Day! Would you like a practice program?
no
try again.
yes
Here's your number: 3

答案 3 :(得分:1)

您可以在案例陈述中使用正则表达式作为测试,尾随i表示不区分大小写。

require 'readline'

choices = Array(1..5)

prompt = "Good Day! Would you like a practice program?"

loop do
  case Readline.readline(prompt + "\n")
  when /yes/i
    puts "Here's your number: #{choices.sample}"
    break
  else
    prompt = 'Try again:'
  end
end

答案 4 :(得分:0)

上述答案的另一种选择可能就是这样。

['Yes'.downcase].include? response.downcase #=> 

编辑:有效评论后的更好版本

['yes'].include? response.downcase #=> true for "yEs"