ruby 是否有www.example.com的反义词String.next?[重复]

46qrfjad  于 2023-05-22  发布在  Ruby
关注(0)|答案(1)|浏览(110)

此问题已在此处有答案

What is the opposite of string.next?(1个答案)
9年前关闭。
Ruby中next的反义词是什么?我试图找到一个类似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"
r1zk6ea1

r1zk6ea11#

如果您的案例仅限于唯一字符,则以下内容将允许您获取上一个或下一个字符:

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可能实现。
参考:

相关问题