能够对整数调用 to_i 的目的是什么?
What is the purpose of being able to call to_i on an Integer?
Ruby 允许使用 Integer.to_s(base) 和 String.to_i(base) 在基数之间进行转换。
我希望使用 Integer.to_i(base) 将二进制整数转换为十进制整数,但这显然不起作用
100.to_i(2)
ArgumentError: wrong number of arguments (1 for 0)
然而,运行
Integer.respond_to? :to_i
给出一个真实的值。为什么会这样?在不同基数的整数之间进行转换的更简单方法是什么?
错误是因为 Integer#to_i
接受 0 个参数,而不是 1 个。
要获取 100
的二进制值,请使用二进制文字 0b100
:
0b100
# => 4
或者先转成字符串:
100.to_s.to_i(2)
# => 4
一个整数已经同时存在于所有基数中。 base(something) 表示仅对字符串有意义。整数只是一个值,10(10) 与 1010(2).
相同
只回答问题的标题:
What is the purpose of being able to call to_i on an Integer?
主要是为了让需要Integer的方法可以接受String
s,Float
s等类型,然后coerce到需要的形式,无需显式检测 class.
def method_that_needs_int( param )
n = param.to_i
# . . . whatever we want to do with n
end
Integer#to_i
本质上是一个 no-op,但它可以使您的代码更简单,只要存在这种情况即可。
来自ruby-doc.org
to_i → integer
As int is already an Integer, all these methods simply return the
receiver.
Synonyms are to_int, floor, ceil, truncate.
方法源代码
static VALUE
int_to_i(VALUE num)
{
return num;
}
所以没有任何目的。
Ruby 允许使用 Integer.to_s(base) 和 String.to_i(base) 在基数之间进行转换。
我希望使用 Integer.to_i(base) 将二进制整数转换为十进制整数,但这显然不起作用
100.to_i(2)
ArgumentError: wrong number of arguments (1 for 0)
然而,运行
Integer.respond_to? :to_i
给出一个真实的值。为什么会这样?在不同基数的整数之间进行转换的更简单方法是什么?
错误是因为 Integer#to_i
接受 0 个参数,而不是 1 个。
要获取 100
的二进制值,请使用二进制文字 0b100
:
0b100
# => 4
或者先转成字符串:
100.to_s.to_i(2)
# => 4
一个整数已经同时存在于所有基数中。 base(something) 表示仅对字符串有意义。整数只是一个值,10(10) 与 1010(2).
相同只回答问题的标题:
What is the purpose of being able to call to_i on an Integer?
主要是为了让需要Integer的方法可以接受String
s,Float
s等类型,然后coerce到需要的形式,无需显式检测 class.
def method_that_needs_int( param )
n = param.to_i
# . . . whatever we want to do with n
end
Integer#to_i
本质上是一个 no-op,但它可以使您的代码更简单,只要存在这种情况即可。
来自ruby-doc.org
to_i → integer
As int is already an Integer, all these methods simply return the receiver. Synonyms are to_int, floor, ceil, truncate.
方法源代码
static VALUE
int_to_i(VALUE num)
{
return num;
}
所以没有任何目的。