我如何错误使用read_string?

时间:2019-03-18 05:54:06

标签: ruby

该程序旨在询问许多问题,然后将输入的信息显示回去。在以前的版本中,我在各个地方都使用了gets.chomp.to_s,并且可以正常工作。但是跟随老师,我将gets.chomp.to_s替换为read_string,现在我的程序无法正常工作。

require 'date'
INCHEs = 0.393701

def main
  first_name = read_string ('What is your first name')
  puts 'Your name is ' + first_name + '!'
  puts 'What is your family name?'
  family_name = gets.chomp.to_s
  puts 'Your family name is: ' + family_name + '!'      
  puts 'What year were you born?'
  year_born = read_string('What year were you born?')
  year_born.to_i
  # Calculate the users age
  current_year = 2019
  age = current_year - year_born
  puts 'So you are ' + age.to_s + ' years old'          
  value_in_cms = read_string('Enter your height in cms (i.e as a float): ')
  value_in_cms.to_f
  value_in_inch = value_in_cms * INCHES
  puts 'Your height in inches is: '
  puts value_in_inch.to_s       
  answer = read_string('Do you wish to continue')
  case answer
  when 'y', 'yes', 'Yes', 'YES'
    true
    puts 'Okay let us continue'
  else
    false
    puts 'Okay, goodbye'
  end
end

main
puts ' '
puts main

我在哪里出错?

2 个答案:

答案 0 :(得分:1)

我认为您最好与老师确认。 在红宝石中没有Image-Button的方法。也许您的老师希望您用read_string方法包装逻辑。

答案 1 :(得分:1)

边注: to_s中的gets.chomp.to_s是多余的,因为gets总是自己返回一个字符串。

您的老师的意思可能是您应该将对gets.chomp的几个调用提取到方法中,并在各处而不是像以前那样gets.chomp使用此方法:

def read_string(prompt)
  print(prompt + " ")
  gets.chomp
end

def main
  first_name = read_string('What is your first name')
  ...
end

注释#2:永远不要在方法名称和红宝石的左括号之间放置空格。