加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

(Ruby)为什么这样做?

发布时间:2020-12-17 01:36:56 所属栏目:百科 来源:网络整理
导读:我最近开始学习 ruby并且正在构建一个简单的“加密”方法.我得到了理想的结果,但我不确定为什么. string = "This is a test"offset = 5def encode(string,offset) coded = "" string.scan(/./) do |char| numbers = char.ord if numbers == 32 numbers = num
我最近开始学习 ruby并且正在构建一个简单的“加密”方法.我得到了理想的结果,但我不确定为什么.

string = "This is a test"
offset = 5

def encode(string,offset)
    coded = ""
    string.scan(/./) do |char|
        numbers = char.ord
        if numbers == 32
            numbers = numbers
        else
            numbers = numbers + offset
        end
        coded << numbers
    end
    return coded
end

puts encode(string,offset)

我得到了所需的编码输出:“Ymnx nx f yjxy”,但我不知道为什么.我期待一串数字,因为我从未指定将这些字母转回字母.有人可以解释一下发生了什么吗?

解决方法

Doc for String#<<

Append—Concatenates the given object to str. If the object is an Integer,it is considered as a codepoint,and is converted to a character before concatenation. Concat can take multiple arguments. All the arguments are concatenated in order.

原始字符串中的字符转换为序数整数,与偏移量一起添加,然后输入字符串#<<方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读