我想像 'a' + 2 = 'c' 这样写,所以我写道:
('a'.ord + 2).chr
是的,我得到了“c”。
但它看起来很多余。有没有更好的直接方法来做到这一点?使用 1.9.3
最佳答案
一个非常非常糟糕的方法是这样的:
class String
alias_method :original_plus, :+
def +(other)
if self.length == 1 and other.is_a?(Fixnum)
(self.ord + other).chr
else
original_plus(other)
end
end
end
puts 'a' + 2
=> c
关于ruby - 获取与另一个偏移的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10247440/