为什么 032 与 Ruby 中的 32 不同? [英] Why is 032 different than 32 in Ruby?

查看:45
本文介绍了为什么 032 与 Ruby 中的 32 不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 Ruby 在使用 032 和 32 时的行为有所不同.我曾经因为在我的代码中使用 032 而不是 32 而出现语法错误.谁可以给我解释一下这个?还是我的代码本身真的有问题?

I have noticed Ruby behaves differently when working with 032 and 32. I once got syntax errors for having 032 instead of just 32 in my code. Can someone explain this to me? Or is there something really wrong with my code itself?

推荐答案

你看到的是 032 是八进制表示,而 32 是十进制:

What you're seeing is 032 is an octal representation, and 32 is decimal:

>> 032 #=> 26
>> 32 #=> 32
>> "32".to_i(8) #=> 26
>> "32".to_i(10) #=> 32

而且,为了完整起见,您可能需要处理十六进制:

And, just for completeness, you might need to deal with hexadecimal:

>> 0x32 #=> 50
>> "32".to_i(16) #=> 50

和二进制:

>> 0b100000 #=> 32
>> 32.to_s(2) #=> "100000"

这篇关于为什么 032 与 Ruby 中的 32 不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆