如何在Ruby中将字符串转换为整数

时间:2011-01-28 17:23:52

标签: ruby

我是ruby的新手,我正在尝试将字符串转换为整数。

我正在尝试计算GPA,因此我使用获取输入字母等级(A,B,C等)然后我将每个转换为各自的数字等级(A = 4,B = 3) ,C = 2等)。我已经找到了一堆关于如何将整数转换为字符串而不是字符串转换为整数的信息。有什么建议吗?

puts ("This program will calculate your GPA this semester")    
puts ("Please type your grade, then press enter")

puts("How many courses are you taking?")
num_courses=gets.chomp
puts("Your are taking #{num_courses} courses")

puts ("Use A, A-, B+, B, B-, C+, C, C-, D, or F (Press enter after typing each grade.)")

gradeList = []
gradeList.push gets.chomp while gradeList.last != ''
puts gradeList.sort

"A"=4
"A-"=3.7
"B+"=3.3

更新:完全更改了代码。我想我是从错误的角度来看它。但是,我仍然收到一个错误:grades.rb:10:nil的未定义方法`last':NilClass(NoMethodError)

puts "This program will calculate your GPA this semester"
puts "Please type your grade, then press enter"

puts("How many courses are you taking?")
num_courses=gets.chomp
puts("Your are taking #{num_courses} courses")

puts ("Use A, A-, B+, B, B-, C+, C, C-, D, or F (Press enter after typing each grade.)")

grade=gets.chomp while grade.last != ''

if grade == "A"
  total=total+4
elsif grade=="B"
  total=total+3
elsif grade=="C"
  total=total+2
elsif grade=="D"
  total=total+1
end

gpa=total/num_courses
puts"Your GPA is #{gpa}"

2 个答案:

答案 0 :(得分:2)

这里最简单的解决方案可能是哈希:

GRADE_VALUES = {
  "A" => 4,
  "A-" => 3.7,
  ...
}

gradeList = []
gradeList.push GRADE_VALUES[gets.chomp.strip] while gradeList.last != ''


puts gradeList

=> [3.7, 4, 3.3 ... ]

答案 1 :(得分:2)

您收到该错误的原因是因为在第一次迭代时未定义grade。您没有意识到这一点,因为您在操作后定位了while。你应该像这样写

while grade.last != '' {
  grade=gets.chomp
}

现在,除了这个循环没有做你想要的任何事情之外,这个形式要好得多,因为在评估时,等级显然是nil

以下是您的代码的快速重写...

puts "This program will calculate your GPA this semester"

puts "How many courses are you taking?"
num_courses = gets.chomp.to_i                    # num_courses is now an integer
puts "You are taking #{num_courses} courses"     # let's pretend num_courses = 4

puts "Use A, A-, B+, B, B-, C+, C, C-, D, or F"

values = {                          # using a hash will allow us to avoid a
    "A" => 4,                       # large and inefficient if / elsif statement
    "A-" => 3.7,
    "B+" => 3.3,
    "B" => 3,
}

total = 0.0                         # sets our total prior to the loop for scope
num_courses.times do                # so we will do this loop 4 times
    total += values[gets.chomp.upcase]       # looks up the value from our hash
end                                          # and adds it to the (running) total

gpa = total / num_courses           # calculates the gpa from the total
                                    # and the num_courses we asked earlier
puts "Your GPA is #{gpa}"

还有其他一些方法可以做到这一点,但希望上述内容足够简单,你可以看到你以前可能难以掌握的一般概念。

我希望这会对你有所帮助,但要问你可能仍会怀疑的任何事情。