Ruby 中的 i.to_s 是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8209194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the meaning of i.to_s in Ruby?
提问by Kishore Babu Jetty
I want to understand a piece of code I found in Google:
我想了解我在谷歌中找到的一段代码:
i.to_s
In the above code iis an integer. As per my understanding iis being converted into a string. Is that true?
在上面的代码中i是一个整数。根据我的理解i正在转换为字符串。真的吗?
回答by Ray Toal
Better to say that this is an expression returning the string representation of the integer i. The integer itself doesn't change. #pedantic.
最好说这是一个返回整数的字符串表示的表达式i。整数本身不会改变。#迂腐。
In irb
在 irb
>> 54.to_s
=> "54"
>> 4598734598734597345937423647234.to_s
=> "4598734598734597345937423647234"
>> i = 7
=> 7
>> i.to_s
=> "7"
>> i
=> 7
回答by koanima
As noted in the other answers, calling .to_s on an integer will return the string representation of that integer.
如其他答案中所述,对整数调用 .to_s 将返回该整数的字符串表示形式。
9.class #=> Fixnum
9.to_s #=> "9"
9.to_s.class #=> String
But you can also pass an argument to .to_s to change it from the default Base = 10 to anything from Base 2 to Base 36. Here is the documentation: Fixnum to_s. So, for example, if you wanted to convert the number 1024 to it's equivalent in binary (aka Base 2, which uses only "1" and "0" to represent any number), you could do:
但是您也可以将参数传递给 .to_s 以将其从默认的 Base = 10 更改为从 Base 2 到 Base 36 的任何内容。这是文档:Fixnum to_s。因此,例如,如果您想将数字 1024 转换为等效的二进制数(又名基数 2,它仅使用“1”和“0”来表示任何数字),您可以执行以下操作:
1024.to_s(2) #=> "10000000000"
Converting to Base 36 can be useful when you want to generate random combinations of letters and numbers, since it counts using every number from 0 to 9 and then every letter from a to z. Base 36 explanation on Wikipedia. For example, the following code will give you a random string of letters and numbers of length 1 to 3 characters long (change the 3 to whatever maximum string length you want, which increases the possible combinations):
当您想要生成字母和数字的随机组合时,转换为 Base 36 会很有用,因为它使用从 0 到 9 的每个数字以及从 a 到 z 的每个字母进行计数。基于维基百科的 36 解释。例如,以下代码将为您提供长度为 1 到 3 个字符的随机字母和数字字符串(将 3 更改为您想要的任何最大字符串长度,这会增加可能的组合):
rand(36**3).to_s(36)
To better understand how the numbers are written in the different base systems, put this code into irb, changing out the 36 in the parenthesis for the base system you want to learn about. The resulting printout will count from 0 to 35 in which ever base system you chose
为了更好地理解不同基础系统中数字的书写方式,请将这段代码放入 irb 中,将括号中的 36 更改为您想了解的基础系统。在您选择的任何基本系统中,生成的打印输出将从 0 计数到 35
36.times {|i| puts i.to_s(36)}
回答by markijbema
That is correct. to_sconverts any object to a string, in this case (probably) an integer, since the variable is called i.
那是正确的。to_s将任何对象转换为字符串,在这种情况下(可能)是整数,因为变量被称为i。

