【问题标题】:Is there an opposite of String.next? [duplicate]有没有 String.next 的反义词? [复制]
【发布时间】:2013-05-28 20:48:23
【问题描述】:

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"

【问题讨论】:

  • 没有这样的事,here 就是原因。

标签: ruby syntax next


【解决方案1】:

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

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 以了解可能的实现。

参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 2021-12-10
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    相关资源
    最近更新 更多