1

nextRubyの反対語は何ですか? prev存在しないような関数を見つけようとしています。

"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"
4

1 に答える 1

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')

ただし、成績を扱う場合は、一種の成績の列挙を使用します。たとえば、可能な実装については、そのブログ投稿をご覧ください。

参照:

于 2013-05-29T07:47:36.907 に答える