2013-05-28 33 views
1

Ruby中的next與之相反的是什麼? 我試圖找到一個不存在的函數,如prev是否存在與String.next相反的內容?

"b".prev將== "a",就像"a".next == "b"

# A grad student at a local university thinks he has discovered a formula to 
# predict what kind of grades a person will get. He says if you own less than 
# 10 books, you will get a "D". If you own 10 to 20 books, you will get a "C", 
# and if you own more than 20 books, you will get a "B". 
# He further hypothesizes that if you actually read your books, then you will 
# get a full letter grade higher in every case. 
# 
# grade(4, false) # => "D" 
# grade(4, true) # => "C" 
# grade(15, true) # => "B" 
+3

有沒有像這一點,[這裏](http://stackoverflow.com/questions/16716522/opposite-字符串中的下一個在紅寶石)是原因。 – squiguy

回答

3

如果你的情況是有限的,以獨特的性格下面將讓你得到以前 或下一個字符:

def next_char(c) 
    (c.chr.ord + 1).chr 
end 

def prev_char(c) 
    (c.chr.ord - 1). chr 
end 

puts next_char('A') 
puts prev_char('B') 

但是,當你處理成績時,我會選擇一個等級的枚舉。例如,看看blog post可能的實現。

編號:

相關問題